OSDN Git Service

Merge "Include tracking state bits to DvrPose." into oc-dr1-dev am: 0d346a0cb1
[android-x86/frameworks-native.git] / services / surfaceflinger / Layer.cpp
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
17 //#define LOG_NDEBUG 0
18 #undef LOG_TAG
19 #define LOG_TAG "Layer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22 #include <stdlib.h>
23 #include <stdint.h>
24 #include <sys/types.h>
25 #include <math.h>
26
27 #include <cutils/compiler.h>
28 #include <cutils/native_handle.h>
29 #include <cutils/properties.h>
30
31 #include <utils/Errors.h>
32 #include <utils/Log.h>
33 #include <utils/NativeHandle.h>
34 #include <utils/StopWatch.h>
35 #include <utils/Trace.h>
36
37 #include <ui/DebugUtils.h>
38 #include <ui/GraphicBuffer.h>
39 #include <ui/PixelFormat.h>
40
41 #include <gui/BufferItem.h>
42 #include <gui/BufferQueue.h>
43 #include <gui/Surface.h>
44
45 #include "clz.h"
46 #include "Colorizer.h"
47 #include "DisplayDevice.h"
48 #include "Layer.h"
49 #include "LayerRejecter.h"
50 #include "MonitoredProducer.h"
51 #include "SurfaceFlinger.h"
52
53 #include "DisplayHardware/HWComposer.h"
54
55 #include "RenderEngine/RenderEngine.h"
56
57 #include <mutex>
58
59 #define DEBUG_RESIZE    0
60
61 namespace android {
62
63 // ---------------------------------------------------------------------------
64
65 int32_t Layer::sSequence = 1;
66
67 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68         const String8& name, uint32_t w, uint32_t h, uint32_t flags)
69     :   contentDirty(false),
70         sequence(uint32_t(android_atomic_inc(&sSequence))),
71         mFlinger(flinger),
72         mTextureName(-1U),
73         mPremultipliedAlpha(true),
74         mName("unnamed"),
75         mFormat(PIXEL_FORMAT_NONE),
76         mTransactionFlags(0),
77         mPendingStateMutex(),
78         mPendingStates(),
79         mQueuedFrames(0),
80         mSidebandStreamChanged(false),
81         mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
82         mCurrentTransform(0),
83         mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
84         mOverrideScalingMode(-1),
85         mCurrentOpacity(true),
86         mBufferLatched(false),
87         mCurrentFrameNumber(0),
88         mPreviousFrameNumber(0),
89         mRefreshPending(false),
90         mFrameLatencyNeeded(false),
91         mFiltering(false),
92         mNeedsFiltering(false),
93         mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
94 #ifndef USE_HWC2
95         mIsGlesComposition(false),
96 #endif
97         mProtectedByApp(false),
98         mHasSurface(false),
99         mClientRef(client),
100         mPotentialCursor(false),
101         mQueueItemLock(),
102         mQueueItemCondition(),
103         mQueueItems(),
104         mLastFrameNumberReceived(0),
105         mUpdateTexImageFailed(false),
106         mAutoRefresh(false),
107         mFreezeGeometryUpdates(false)
108 {
109 #ifdef USE_HWC2
110     ALOGV("Creating Layer %s", name.string());
111 #endif
112
113     mCurrentCrop.makeInvalid();
114     mFlinger->getRenderEngine().genTextures(1, &mTextureName);
115     mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
116
117     uint32_t layerFlags = 0;
118     if (flags & ISurfaceComposerClient::eHidden)
119         layerFlags |= layer_state_t::eLayerHidden;
120     if (flags & ISurfaceComposerClient::eOpaque)
121         layerFlags |= layer_state_t::eLayerOpaque;
122     if (flags & ISurfaceComposerClient::eSecure)
123         layerFlags |= layer_state_t::eLayerSecure;
124
125     if (flags & ISurfaceComposerClient::eNonPremultiplied)
126         mPremultipliedAlpha = false;
127
128     mName = name;
129     mTransactionName = String8("TX - ") + mName;
130
131     mCurrentState.active.w = w;
132     mCurrentState.active.h = h;
133     mCurrentState.active.transform.set(0, 0);
134     mCurrentState.crop.makeInvalid();
135     mCurrentState.finalCrop.makeInvalid();
136     mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
137     mCurrentState.requestedCrop = mCurrentState.crop;
138     mCurrentState.z = 0;
139 #ifdef USE_HWC2
140     mCurrentState.alpha = 1.0f;
141 #else
142     mCurrentState.alpha = 0xFF;
143 #endif
144     mCurrentState.layerStack = 0;
145     mCurrentState.flags = layerFlags;
146     mCurrentState.sequence = 0;
147     mCurrentState.requested = mCurrentState.active;
148     mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
149     mCurrentState.appId = 0;
150     mCurrentState.type = 0;
151
152     // drawing state & current state are identical
153     mDrawingState = mCurrentState;
154
155 #ifdef USE_HWC2
156     const auto& hwc = flinger->getHwComposer();
157     const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
158     nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
159 #else
160     nsecs_t displayPeriod =
161             flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
162 #endif
163     mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
164
165     CompositorTiming compositorTiming;
166     flinger->getCompositorTiming(&compositorTiming);
167     mFrameEventHistory.initializeCompositorTiming(compositorTiming);
168 }
169
170 void Layer::onFirstRef() {
171     // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
172     sp<IGraphicBufferProducer> producer;
173     sp<IGraphicBufferConsumer> consumer;
174     BufferQueue::createBufferQueue(&producer, &consumer, true);
175     mProducer = new MonitoredProducer(producer, mFlinger, this);
176     mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
177     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
178     mSurfaceFlingerConsumer->setContentsChangedListener(this);
179     mSurfaceFlingerConsumer->setName(mName);
180
181     if (mFlinger->isLayerTripleBufferingDisabled()) {
182         mProducer->setMaxDequeuedBufferCount(2);
183     }
184
185     const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
186     updateTransformHint(hw);
187 }
188
189 Layer::~Layer() {
190   sp<Client> c(mClientRef.promote());
191     if (c != 0) {
192         c->detachLayer(this);
193     }
194
195     for (auto& point : mRemoteSyncPoints) {
196         point->setTransactionApplied();
197     }
198     for (auto& point : mLocalSyncPoints) {
199         point->setFrameAvailable();
200     }
201     mFlinger->deleteTextureAsync(mTextureName);
202     mFrameTracker.logAndResetStats(mName);
203 }
204
205 // ---------------------------------------------------------------------------
206 // callbacks
207 // ---------------------------------------------------------------------------
208
209 #ifdef USE_HWC2
210 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
211     if (mHwcLayers.empty()) {
212         return;
213     }
214     mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
215 }
216 #else
217 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
218         HWComposer::HWCLayerInterface* layer) {
219     if (layer) {
220         layer->onDisplayed();
221         mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
222     }
223 }
224 #endif
225
226 void Layer::onFrameAvailable(const BufferItem& item) {
227     // Add this buffer from our internal queue tracker
228     { // Autolock scope
229         Mutex::Autolock lock(mQueueItemLock);
230         mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
231                 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
232         // Reset the frame number tracker when we receive the first buffer after
233         // a frame number reset
234         if (item.mFrameNumber == 1) {
235             mLastFrameNumberReceived = 0;
236         }
237
238         // Ensure that callbacks are handled in order
239         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
240             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
241                     ms2ns(500));
242             if (result != NO_ERROR) {
243                 ALOGE("[%s] Timed out waiting on callback", mName.string());
244             }
245         }
246
247         mQueueItems.push_back(item);
248         android_atomic_inc(&mQueuedFrames);
249
250         // Wake up any pending callbacks
251         mLastFrameNumberReceived = item.mFrameNumber;
252         mQueueItemCondition.broadcast();
253     }
254
255     mFlinger->signalLayerUpdate();
256 }
257
258 void Layer::onFrameReplaced(const BufferItem& item) {
259     { // Autolock scope
260         Mutex::Autolock lock(mQueueItemLock);
261
262         // Ensure that callbacks are handled in order
263         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
264             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
265                     ms2ns(500));
266             if (result != NO_ERROR) {
267                 ALOGE("[%s] Timed out waiting on callback", mName.string());
268             }
269         }
270
271         if (mQueueItems.empty()) {
272             ALOGE("Can't replace a frame on an empty queue");
273             return;
274         }
275         mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
276
277         // Wake up any pending callbacks
278         mLastFrameNumberReceived = item.mFrameNumber;
279         mQueueItemCondition.broadcast();
280     }
281 }
282
283 void Layer::onSidebandStreamChanged() {
284     if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
285         // mSidebandStreamChanged was false
286         mFlinger->signalLayerUpdate();
287     }
288 }
289
290 // called with SurfaceFlinger::mStateLock from the drawing thread after
291 // the layer has been remove from the current state list (and just before
292 // it's removed from the drawing state list)
293 void Layer::onRemoved() {
294     if (mCurrentState.zOrderRelativeOf != nullptr) {
295         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
296         if (strongRelative != nullptr) {
297             strongRelative->removeZOrderRelative(this);
298         }
299         mCurrentState.zOrderRelativeOf = nullptr;
300     }
301
302     mSurfaceFlingerConsumer->abandon();
303
304 #ifdef USE_HWC2
305     clearHwcLayers();
306 #endif
307
308     for (const auto& child : mCurrentChildren) {
309         child->onRemoved();
310     }
311 }
312
313 // ---------------------------------------------------------------------------
314 // set-up
315 // ---------------------------------------------------------------------------
316
317 const String8& Layer::getName() const {
318     return mName;
319 }
320
321 status_t Layer::setBuffers( uint32_t w, uint32_t h,
322                             PixelFormat format, uint32_t flags)
323 {
324     uint32_t const maxSurfaceDims = min(
325             mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
326
327     // never allow a surface larger than what our underlying GL implementation
328     // can handle.
329     if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
330         ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
331         return BAD_VALUE;
332     }
333
334     mFormat = format;
335
336     mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
337     mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
338     mCurrentOpacity = getOpacityForFormat(format);
339
340     mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
341     mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
342     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
343
344     return NO_ERROR;
345 }
346
347 sp<IBinder> Layer::getHandle() {
348     Mutex::Autolock _l(mLock);
349
350     LOG_ALWAYS_FATAL_IF(mHasSurface,
351             "Layer::getHandle() has already been called");
352
353     mHasSurface = true;
354
355     return new Handle(mFlinger, this);
356 }
357
358 sp<IGraphicBufferProducer> Layer::getProducer() const {
359     return mProducer;
360 }
361
362 // ---------------------------------------------------------------------------
363 // h/w composer set-up
364 // ---------------------------------------------------------------------------
365
366 Rect Layer::getContentCrop() const {
367     // this is the crop rectangle that applies to the buffer
368     // itself (as opposed to the window)
369     Rect crop;
370     if (!mCurrentCrop.isEmpty()) {
371         // if the buffer crop is defined, we use that
372         crop = mCurrentCrop;
373     } else if (mActiveBuffer != NULL) {
374         // otherwise we use the whole buffer
375         crop = mActiveBuffer->getBounds();
376     } else {
377         // if we don't have a buffer yet, we use an empty/invalid crop
378         crop.makeInvalid();
379     }
380     return crop;
381 }
382
383 static Rect reduce(const Rect& win, const Region& exclude) {
384     if (CC_LIKELY(exclude.isEmpty())) {
385         return win;
386     }
387     if (exclude.isRect()) {
388         return win.reduce(exclude.getBounds());
389     }
390     return Region(win).subtract(exclude).getBounds();
391 }
392
393 Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
394     const Layer::State& s(getDrawingState());
395     Rect win(s.active.w, s.active.h);
396
397     if (!s.crop.isEmpty()) {
398         win.intersect(s.crop, &win);
399     }
400
401     Transform t = getTransform();
402     win = t.transform(win);
403
404     if (!s.finalCrop.isEmpty()) {
405         win.intersect(s.finalCrop, &win);
406     }
407
408     const sp<Layer>& p = mDrawingParent.promote();
409     // Now we need to calculate the parent bounds, so we can clip ourselves to those.
410     // When calculating the parent bounds for purposes of clipping,
411     // we don't need to constrain the parent to its transparent region.
412     // The transparent region is an optimization based on the
413     // buffer contents of the layer, but does not affect the space allocated to
414     // it by policy, and thus children should be allowed to extend into the
415     // parent's transparent region. In fact one of the main uses, is to reduce
416     // buffer allocation size in cases where a child window sits behind a main window
417     // (by marking the hole in the parent window as a transparent region)
418     if (p != nullptr) {
419         Rect bounds = p->computeScreenBounds(false);
420         bounds.intersect(win, &win);
421     }
422
423     if (reduceTransparentRegion) {
424         auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
425         win = reduce(win, screenTransparentRegion);
426     }
427
428     return win;
429 }
430
431 Rect Layer::computeBounds() const {
432     const Layer::State& s(getDrawingState());
433     return computeBounds(s.activeTransparentRegion);
434 }
435
436 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
437     const Layer::State& s(getDrawingState());
438     Rect win(s.active.w, s.active.h);
439
440     if (!s.crop.isEmpty()) {
441         win.intersect(s.crop, &win);
442     }
443
444     Rect bounds = win;
445     const auto& p = mDrawingParent.promote();
446     if (p != nullptr) {
447         // Look in computeScreenBounds recursive call for explanation of
448         // why we pass false here.
449         bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
450     }
451
452     Transform t = getTransform();
453     if (p != nullptr) {
454         win = t.transform(win);
455         win.intersect(bounds, &win);
456         win = t.inverse().transform(win);
457     }
458
459     // subtract the transparent region and snap to the bounds
460     return reduce(win, activeTransparentRegion);
461 }
462
463 Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
464     // the crop is the area of the window that gets cropped, but not
465     // scaled in any ways.
466     const State& s(getDrawingState());
467
468     // apply the projection's clipping to the window crop in
469     // layerstack space, and convert-back to layer space.
470     // if there are no window scaling involved, this operation will map to full
471     // pixels in the buffer.
472     // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
473     // a viewport clipping and a window transform. we should use floating point to fix this.
474
475     Rect activeCrop(s.active.w, s.active.h);
476     if (!s.crop.isEmpty()) {
477         activeCrop = s.crop;
478     }
479
480     Transform t = getTransform();
481     activeCrop = t.transform(activeCrop);
482     if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
483         activeCrop.clear();
484     }
485     if (!s.finalCrop.isEmpty()) {
486         if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
487             activeCrop.clear();
488         }
489     }
490     return activeCrop;
491 }
492
493 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
494     // the content crop is the area of the content that gets scaled to the
495     // layer's size. This is in buffer space.
496     FloatRect crop = getContentCrop().toFloatRect();
497
498     // In addition there is a WM-specified crop we pull from our drawing state.
499     const State& s(getDrawingState());
500
501     // Screen space to make reduction to parent crop clearer.
502     Rect activeCrop = computeInitialCrop(hw);
503     const auto& p = mDrawingParent.promote();
504     if (p != nullptr) {
505         auto parentCrop = p->computeInitialCrop(hw);
506         activeCrop.intersect(parentCrop, &activeCrop);
507     }
508     Transform t = getTransform();
509     // Back to layer space to work with the content crop.
510     activeCrop = t.inverse().transform(activeCrop);
511
512     // This needs to be here as transform.transform(Rect) computes the
513     // transformed rect and then takes the bounding box of the result before
514     // returning. This means
515     // transform.inverse().transform(transform.transform(Rect)) != Rect
516     // in which case we need to make sure the final rect is clipped to the
517     // display bounds.
518     if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
519         activeCrop.clear();
520     }
521
522     // subtract the transparent region and snap to the bounds
523     activeCrop = reduce(activeCrop, s.activeTransparentRegion);
524
525     // Transform the window crop to match the buffer coordinate system,
526     // which means using the inverse of the current transform set on the
527     // SurfaceFlingerConsumer.
528     uint32_t invTransform = mCurrentTransform;
529     if (getTransformToDisplayInverse()) {
530         /*
531          * the code below applies the primary display's inverse transform to the
532          * buffer
533          */
534         uint32_t invTransformOrient =
535                 DisplayDevice::getPrimaryDisplayOrientationTransform();
536         // calculate the inverse transform
537         if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538             invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
539                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
540         }
541         // and apply to the current transform
542         invTransform = (Transform(invTransformOrient) * Transform(invTransform))
543                 .getOrientation();
544     }
545
546     int winWidth = s.active.w;
547     int winHeight = s.active.h;
548     if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
549         // If the activeCrop has been rotate the ends are rotated but not
550         // the space itself so when transforming ends back we can't rely on
551         // a modification of the axes of rotation. To account for this we
552         // need to reorient the inverse rotation in terms of the current
553         // axes of rotation.
554         bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
555         bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
556         if (is_h_flipped == is_v_flipped) {
557             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
558                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
559         }
560         winWidth = s.active.h;
561         winHeight = s.active.w;
562     }
563     const Rect winCrop = activeCrop.transform(
564             invTransform, s.active.w, s.active.h);
565
566     // below, crop is intersected with winCrop expressed in crop's coordinate space
567     float xScale = crop.getWidth()  / float(winWidth);
568     float yScale = crop.getHeight() / float(winHeight);
569
570     float insetL = winCrop.left                 * xScale;
571     float insetT = winCrop.top                  * yScale;
572     float insetR = (winWidth - winCrop.right )  * xScale;
573     float insetB = (winHeight - winCrop.bottom) * yScale;
574
575     crop.left   += insetL;
576     crop.top    += insetT;
577     crop.right  -= insetR;
578     crop.bottom -= insetB;
579
580     return crop;
581 }
582
583 #ifdef USE_HWC2
584 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
585 #else
586 void Layer::setGeometry(
587     const sp<const DisplayDevice>& hw,
588         HWComposer::HWCLayerInterface& layer)
589 #endif
590 {
591 #ifdef USE_HWC2
592     const auto hwcId = displayDevice->getHwcDisplayId();
593     auto& hwcInfo = mHwcLayers[hwcId];
594 #else
595     layer.setDefaultState();
596 #endif
597
598     // enable this layer
599 #ifdef USE_HWC2
600     hwcInfo.forceClientComposition = false;
601
602     if (isSecure() && !displayDevice->isSecure()) {
603         hwcInfo.forceClientComposition = true;
604     }
605
606     auto& hwcLayer = hwcInfo.layer;
607 #else
608     layer.setSkip(false);
609
610     if (isSecure() && !hw->isSecure()) {
611         layer.setSkip(true);
612     }
613 #endif
614
615     // this gives us only the "orientation" component of the transform
616     const State& s(getDrawingState());
617 #ifdef USE_HWC2
618     auto blendMode = HWC2::BlendMode::None;
619     if (!isOpaque(s) || getAlpha() != 1.0f) {
620         blendMode = mPremultipliedAlpha ?
621                 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
622     }
623     auto error = hwcLayer->setBlendMode(blendMode);
624     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
625              " %s (%d)", mName.string(), to_string(blendMode).c_str(),
626              to_string(error).c_str(), static_cast<int32_t>(error));
627 #else
628     if (!isOpaque(s) || getAlpha() != 0xFF) {
629         layer.setBlending(mPremultipliedAlpha ?
630                 HWC_BLENDING_PREMULT :
631                 HWC_BLENDING_COVERAGE);
632     }
633 #endif
634
635     // apply the layer's transform, followed by the display's global transform
636     // here we're guaranteed that the layer's transform preserves rects
637     Region activeTransparentRegion(s.activeTransparentRegion);
638     Transform t = getTransform();
639     if (!s.crop.isEmpty()) {
640         Rect activeCrop(s.crop);
641         activeCrop = t.transform(activeCrop);
642 #ifdef USE_HWC2
643         if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
644 #else
645         if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
646 #endif
647             activeCrop.clear();
648         }
649         activeCrop = t.inverse().transform(activeCrop, true);
650         // This needs to be here as transform.transform(Rect) computes the
651         // transformed rect and then takes the bounding box of the result before
652         // returning. This means
653         // transform.inverse().transform(transform.transform(Rect)) != Rect
654         // in which case we need to make sure the final rect is clipped to the
655         // display bounds.
656         if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
657             activeCrop.clear();
658         }
659         // mark regions outside the crop as transparent
660         activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
661         activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
662                 s.active.w, s.active.h));
663         activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
664                 activeCrop.left, activeCrop.bottom));
665         activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
666                 s.active.w, activeCrop.bottom));
667     }
668
669     Rect frame(t.transform(computeBounds(activeTransparentRegion)));
670     if (!s.finalCrop.isEmpty()) {
671         if(!frame.intersect(s.finalCrop, &frame)) {
672             frame.clear();
673         }
674     }
675 #ifdef USE_HWC2
676     if (!frame.intersect(displayDevice->getViewport(), &frame)) {
677         frame.clear();
678     }
679     const Transform& tr(displayDevice->getTransform());
680     Rect transformedFrame = tr.transform(frame);
681     error = hwcLayer->setDisplayFrame(transformedFrame);
682     if (error != HWC2::Error::None) {
683         ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
684                 mName.string(), transformedFrame.left, transformedFrame.top,
685                 transformedFrame.right, transformedFrame.bottom,
686                 to_string(error).c_str(), static_cast<int32_t>(error));
687     } else {
688         hwcInfo.displayFrame = transformedFrame;
689     }
690
691     FloatRect sourceCrop = computeCrop(displayDevice);
692     error = hwcLayer->setSourceCrop(sourceCrop);
693     if (error != HWC2::Error::None) {
694         ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
695                 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
696                 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
697                 static_cast<int32_t>(error));
698     } else {
699         hwcInfo.sourceCrop = sourceCrop;
700     }
701
702     float alpha = getAlpha();
703     error = hwcLayer->setPlaneAlpha(alpha);
704     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
705             "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
706             static_cast<int32_t>(error));
707
708     error = hwcLayer->setZOrder(z);
709     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
710             mName.string(), z, to_string(error).c_str(),
711             static_cast<int32_t>(error));
712
713     int type = s.type;
714     int appId = s.appId;
715     sp<Layer> parent = mDrawingParent.promote();
716     if (parent.get()) {
717         auto& parentState = parent->getDrawingState();
718         type = parentState.type;
719         appId = parentState.appId;
720     }
721
722     error = hwcLayer->setInfo(type, appId);
723     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
724              mName.string(), static_cast<int32_t>(error));
725 #else
726     if (!frame.intersect(hw->getViewport(), &frame)) {
727         frame.clear();
728     }
729     const Transform& tr(hw->getTransform());
730     layer.setFrame(tr.transform(frame));
731     layer.setCrop(computeCrop(hw));
732     layer.setPlaneAlpha(getAlpha());
733 #endif
734
735     /*
736      * Transformations are applied in this order:
737      * 1) buffer orientation/flip/mirror
738      * 2) state transformation (window manager)
739      * 3) layer orientation (screen orientation)
740      * (NOTE: the matrices are multiplied in reverse order)
741      */
742
743     const Transform bufferOrientation(mCurrentTransform);
744     Transform transform(tr * t * bufferOrientation);
745
746     if (getTransformToDisplayInverse()) {
747         /*
748          * the code below applies the primary display's inverse transform to the
749          * buffer
750          */
751         uint32_t invTransform =
752                 DisplayDevice::getPrimaryDisplayOrientationTransform();
753         // calculate the inverse transform
754         if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
755             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
756                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
757         }
758
759         /*
760          * Here we cancel out the orientation component of the WM transform.
761          * The scaling and translate components are already included in our bounds
762          * computation so it's enough to just omit it in the composition.
763          * See comment in onDraw with ref to b/36727915 for why.
764          */
765         transform = Transform(invTransform) * tr * bufferOrientation;
766     }
767
768     // this gives us only the "orientation" component of the transform
769     const uint32_t orientation = transform.getOrientation();
770 #ifdef USE_HWC2
771     if (orientation & Transform::ROT_INVALID) {
772         // we can only handle simple transformation
773         hwcInfo.forceClientComposition = true;
774     } else {
775         auto transform = static_cast<HWC2::Transform>(orientation);
776         auto error = hwcLayer->setTransform(transform);
777         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
778                 "%s (%d)", mName.string(), to_string(transform).c_str(),
779                 to_string(error).c_str(), static_cast<int32_t>(error));
780     }
781 #else
782     if (orientation & Transform::ROT_INVALID) {
783         // we can only handle simple transformation
784         layer.setSkip(true);
785     } else {
786         layer.setTransform(orientation);
787     }
788 #endif
789 }
790
791 #ifdef USE_HWC2
792 void Layer::forceClientComposition(int32_t hwcId) {
793     if (mHwcLayers.count(hwcId) == 0) {
794         ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
795         return;
796     }
797
798     mHwcLayers[hwcId].forceClientComposition = true;
799 }
800
801 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
802     // Apply this display's projection's viewport to the visible region
803     // before giving it to the HWC HAL.
804     const Transform& tr = displayDevice->getTransform();
805     const auto& viewport = displayDevice->getViewport();
806     Region visible = tr.transform(visibleRegion.intersect(viewport));
807     auto hwcId = displayDevice->getHwcDisplayId();
808     auto& hwcInfo = mHwcLayers[hwcId];
809     auto& hwcLayer = hwcInfo.layer;
810     auto error = hwcLayer->setVisibleRegion(visible);
811     if (error != HWC2::Error::None) {
812         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
813                 to_string(error).c_str(), static_cast<int32_t>(error));
814         visible.dump(LOG_TAG);
815     }
816
817     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
818     if (error != HWC2::Error::None) {
819         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
820                 to_string(error).c_str(), static_cast<int32_t>(error));
821         surfaceDamageRegion.dump(LOG_TAG);
822     }
823
824     // Sideband layers
825     if (mSidebandStream.get()) {
826         setCompositionType(hwcId, HWC2::Composition::Sideband);
827         ALOGV("[%s] Requesting Sideband composition", mName.string());
828         error = hwcLayer->setSidebandStream(mSidebandStream->handle());
829         if (error != HWC2::Error::None) {
830             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
831                     mName.string(), mSidebandStream->handle(),
832                     to_string(error).c_str(), static_cast<int32_t>(error));
833         }
834         return;
835     }
836
837     // Client layers
838     if (hwcInfo.forceClientComposition ||
839             (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
840         ALOGV("[%s] Requesting Client composition", mName.string());
841         setCompositionType(hwcId, HWC2::Composition::Client);
842         return;
843     }
844
845     // SolidColor layers
846     if (mActiveBuffer == nullptr) {
847         setCompositionType(hwcId, HWC2::Composition::SolidColor);
848
849         // For now, we only support black for DimLayer
850         error = hwcLayer->setColor({0, 0, 0, 255});
851         if (error != HWC2::Error::None) {
852             ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
853                     to_string(error).c_str(), static_cast<int32_t>(error));
854         }
855
856         // Clear out the transform, because it doesn't make sense absent a
857         // source buffer
858         error = hwcLayer->setTransform(HWC2::Transform::None);
859         if (error != HWC2::Error::None) {
860             ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
861                     to_string(error).c_str(), static_cast<int32_t>(error));
862         }
863
864         return;
865     }
866
867     // Device or Cursor layers
868     if (mPotentialCursor) {
869         ALOGV("[%s] Requesting Cursor composition", mName.string());
870         setCompositionType(hwcId, HWC2::Composition::Cursor);
871     } else {
872         ALOGV("[%s] Requesting Device composition", mName.string());
873         setCompositionType(hwcId, HWC2::Composition::Device);
874     }
875
876     ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
877     error = hwcLayer->setDataspace(mCurrentState.dataSpace);
878     if (error != HWC2::Error::None) {
879         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
880               mCurrentState.dataSpace, to_string(error).c_str(),
881               static_cast<int32_t>(error));
882     }
883
884     uint32_t hwcSlot = 0;
885     sp<GraphicBuffer> hwcBuffer;
886     hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
887             &hwcSlot, &hwcBuffer);
888
889     auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
890     error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
891     if (error != HWC2::Error::None) {
892         ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
893                 mActiveBuffer->handle, to_string(error).c_str(),
894                 static_cast<int32_t>(error));
895     }
896 }
897
898 #else
899 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
900         HWComposer::HWCLayerInterface& layer) {
901     // we have to set the visible region on every frame because
902     // we currently free it during onLayerDisplayed(), which is called
903     // after HWComposer::commit() -- every frame.
904     // Apply this display's projection's viewport to the visible region
905     // before giving it to the HWC HAL.
906     const Transform& tr = hw->getTransform();
907     Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
908     layer.setVisibleRegionScreen(visible);
909     layer.setSurfaceDamage(surfaceDamageRegion);
910     mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
911
912     if (mSidebandStream.get()) {
913         layer.setSidebandStream(mSidebandStream);
914     } else {
915         // NOTE: buffer can be NULL if the client never drew into this
916         // layer yet, or if we ran out of memory
917         layer.setBuffer(mActiveBuffer);
918     }
919 }
920 #endif
921
922 #ifdef USE_HWC2
923 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
924     auto hwcId = displayDevice->getHwcDisplayId();
925     if (mHwcLayers.count(hwcId) == 0 ||
926             getCompositionType(hwcId) != HWC2::Composition::Cursor) {
927         return;
928     }
929
930     // This gives us only the "orientation" component of the transform
931     const State& s(getCurrentState());
932
933     // Apply the layer's transform, followed by the display's global transform
934     // Here we're guaranteed that the layer's transform preserves rects
935     Rect win(s.active.w, s.active.h);
936     if (!s.crop.isEmpty()) {
937         win.intersect(s.crop, &win);
938     }
939     // Subtract the transparent region and snap to the bounds
940     Rect bounds = reduce(win, s.activeTransparentRegion);
941     Rect frame(getTransform().transform(bounds));
942     frame.intersect(displayDevice->getViewport(), &frame);
943     if (!s.finalCrop.isEmpty()) {
944         frame.intersect(s.finalCrop, &frame);
945     }
946     auto& displayTransform(displayDevice->getTransform());
947     auto position = displayTransform.transform(frame);
948
949     auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
950             position.top);
951     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
952             "to (%d, %d): %s (%d)", mName.string(), position.left,
953             position.top, to_string(error).c_str(),
954             static_cast<int32_t>(error));
955 }
956 #else
957 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
958         HWComposer::HWCLayerInterface& layer) {
959     int fenceFd = -1;
960
961     // TODO: there is a possible optimization here: we only need to set the
962     // acquire fence the first time a new buffer is acquired on EACH display.
963
964     if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
965         sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
966         if (fence->isValid()) {
967             fenceFd = fence->dup();
968             if (fenceFd == -1) {
969                 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
970             }
971         }
972     }
973     layer.setAcquireFenceFd(fenceFd);
974 }
975
976 Rect Layer::getPosition(
977     const sp<const DisplayDevice>& hw)
978 {
979     // this gives us only the "orientation" component of the transform
980     const State& s(getCurrentState());
981
982     // apply the layer's transform, followed by the display's global transform
983     // here we're guaranteed that the layer's transform preserves rects
984     Rect win(s.active.w, s.active.h);
985     if (!s.crop.isEmpty()) {
986         win.intersect(s.crop, &win);
987     }
988     // subtract the transparent region and snap to the bounds
989     Rect bounds = reduce(win, s.activeTransparentRegion);
990     Rect frame(getTransform().transform(bounds));
991     frame.intersect(hw->getViewport(), &frame);
992     if (!s.finalCrop.isEmpty()) {
993         frame.intersect(s.finalCrop, &frame);
994     }
995     const Transform& tr(hw->getTransform());
996     return Rect(tr.transform(frame));
997 }
998 #endif
999
1000 // ---------------------------------------------------------------------------
1001 // drawing...
1002 // ---------------------------------------------------------------------------
1003
1004 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
1005     onDraw(hw, clip, false);
1006 }
1007
1008 void Layer::draw(const sp<const DisplayDevice>& hw,
1009         bool useIdentityTransform) const {
1010     onDraw(hw, Region(hw->bounds()), useIdentityTransform);
1011 }
1012
1013 void Layer::draw(const sp<const DisplayDevice>& hw) const {
1014     onDraw(hw, Region(hw->bounds()), false);
1015 }
1016
1017 static constexpr mat4 inverseOrientation(uint32_t transform) {
1018     const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
1019     const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1020     const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1021     mat4 tr;
1022
1023     if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1024         tr = tr * rot90;
1025     }
1026     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1027         tr = tr * flipH;
1028     }
1029     if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1030         tr = tr * flipV;
1031     }
1032     return inverse(tr);
1033 }
1034
1035 /*
1036  * onDraw will draw the current layer onto the presentable buffer
1037  */
1038 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1039         bool useIdentityTransform) const
1040 {
1041     ATRACE_CALL();
1042
1043     if (CC_UNLIKELY(mActiveBuffer == 0)) {
1044         // the texture has not been created yet, this Layer has
1045         // in fact never been drawn into. This happens frequently with
1046         // SurfaceView because the WindowManager can't know when the client
1047         // has drawn the first time.
1048
1049         // If there is nothing under us, we paint the screen in black, otherwise
1050         // we just skip this update.
1051
1052         // figure out if there is something below us
1053         Region under;
1054         bool finished = false;
1055         mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
1056             if (finished || layer == static_cast<Layer const*>(this)) {
1057                 finished = true;
1058                 return;
1059             }
1060             under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1061         });
1062         // if not everything below us is covered, we plug the holes!
1063         Region holes(clip.subtract(under));
1064         if (!holes.isEmpty()) {
1065             clearWithOpenGL(hw, 0, 0, 0, 1);
1066         }
1067         return;
1068     }
1069
1070     // Bind the current buffer to the GL texture, and wait for it to be
1071     // ready for us to draw into.
1072     status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1073     if (err != NO_ERROR) {
1074         ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1075         // Go ahead and draw the buffer anyway; no matter what we do the screen
1076         // is probably going to have something visibly wrong.
1077     }
1078
1079     bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1080
1081     RenderEngine& engine(mFlinger->getRenderEngine());
1082
1083     if (!blackOutLayer) {
1084         // TODO: we could be more subtle with isFixedSize()
1085         const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1086
1087         // Query the texture matrix given our current filtering mode.
1088         float textureMatrix[16];
1089         mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1090         mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1091
1092         if (getTransformToDisplayInverse()) {
1093
1094             /*
1095              * the code below applies the primary display's inverse transform to
1096              * the texture transform
1097              */
1098             uint32_t transform =
1099                     DisplayDevice::getPrimaryDisplayOrientationTransform();
1100             mat4 tr = inverseOrientation(transform);
1101
1102             /**
1103              * TODO(b/36727915): This is basically a hack.
1104              *
1105              * Ensure that regardless of the parent transformation,
1106              * this buffer is always transformed from native display
1107              * orientation to display orientation. For example, in the case
1108              * of a camera where the buffer remains in native orientation,
1109              * we want the pixels to always be upright.
1110              */
1111             sp<Layer> p = mDrawingParent.promote();
1112             if (p != nullptr) {
1113                 const auto parentTransform = p->getTransform();
1114                 tr = tr * inverseOrientation(parentTransform.getOrientation());
1115             }
1116
1117             // and finally apply it to the original texture matrix
1118             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1119             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1120         }
1121
1122         // Set things up for texturing.
1123         mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1124         mTexture.setFiltering(useFiltering);
1125         mTexture.setMatrix(textureMatrix);
1126
1127         engine.setupLayerTexturing(mTexture);
1128     } else {
1129         engine.setupLayerBlackedOut();
1130     }
1131     drawWithOpenGL(hw, useIdentityTransform);
1132     engine.disableTexturing();
1133 }
1134
1135
1136 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1137         float red, float green, float blue,
1138         float alpha) const
1139 {
1140     RenderEngine& engine(mFlinger->getRenderEngine());
1141     computeGeometry(hw, mMesh, false);
1142     engine.setupFillWithColor(red, green, blue, alpha);
1143     engine.drawMesh(mMesh);
1144 }
1145
1146 void Layer::clearWithOpenGL(
1147         const sp<const DisplayDevice>& hw) const {
1148     clearWithOpenGL(hw, 0,0,0,0);
1149 }
1150
1151 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1152         bool useIdentityTransform) const {
1153     const State& s(getDrawingState());
1154
1155     computeGeometry(hw, mMesh, useIdentityTransform);
1156
1157     /*
1158      * NOTE: the way we compute the texture coordinates here produces
1159      * different results than when we take the HWC path -- in the later case
1160      * the "source crop" is rounded to texel boundaries.
1161      * This can produce significantly different results when the texture
1162      * is scaled by a large amount.
1163      *
1164      * The GL code below is more logical (imho), and the difference with
1165      * HWC is due to a limitation of the HWC API to integers -- a question
1166      * is suspend is whether we should ignore this problem or revert to
1167      * GL composition when a buffer scaling is applied (maybe with some
1168      * minimal value)? Or, we could make GL behave like HWC -- but this feel
1169      * like more of a hack.
1170      */
1171     Rect win(computeBounds());
1172
1173     Transform t = getTransform();
1174     if (!s.finalCrop.isEmpty()) {
1175         win = t.transform(win);
1176         if (!win.intersect(s.finalCrop, &win)) {
1177             win.clear();
1178         }
1179         win = t.inverse().transform(win);
1180         if (!win.intersect(computeBounds(), &win)) {
1181             win.clear();
1182         }
1183     }
1184
1185     float left   = float(win.left)   / float(s.active.w);
1186     float top    = float(win.top)    / float(s.active.h);
1187     float right  = float(win.right)  / float(s.active.w);
1188     float bottom = float(win.bottom) / float(s.active.h);
1189
1190     // TODO: we probably want to generate the texture coords with the mesh
1191     // here we assume that we only have 4 vertices
1192     Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1193     texCoords[0] = vec2(left, 1.0f - top);
1194     texCoords[1] = vec2(left, 1.0f - bottom);
1195     texCoords[2] = vec2(right, 1.0f - bottom);
1196     texCoords[3] = vec2(right, 1.0f - top);
1197
1198     RenderEngine& engine(mFlinger->getRenderEngine());
1199     engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1200 #ifdef USE_HWC2
1201     engine.setSourceDataSpace(mCurrentState.dataSpace);
1202 #endif
1203     engine.drawMesh(mMesh);
1204     engine.disableBlending();
1205 }
1206
1207 #ifdef USE_HWC2
1208 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1209         bool callIntoHwc) {
1210     if (mHwcLayers.count(hwcId) == 0) {
1211         ALOGE("setCompositionType called without a valid HWC layer");
1212         return;
1213     }
1214     auto& hwcInfo = mHwcLayers[hwcId];
1215     auto& hwcLayer = hwcInfo.layer;
1216     ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1217             to_string(type).c_str(), static_cast<int>(callIntoHwc));
1218     if (hwcInfo.compositionType != type) {
1219         ALOGV("    actually setting");
1220         hwcInfo.compositionType = type;
1221         if (callIntoHwc) {
1222             auto error = hwcLayer->setCompositionType(type);
1223             ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1224                     "composition type %s: %s (%d)", mName.string(),
1225                     to_string(type).c_str(), to_string(error).c_str(),
1226                     static_cast<int32_t>(error));
1227         }
1228     }
1229 }
1230
1231 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1232     if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1233         // If we're querying the composition type for a display that does not
1234         // have a HWC counterpart, then it will always be Client
1235         return HWC2::Composition::Client;
1236     }
1237     if (mHwcLayers.count(hwcId) == 0) {
1238         ALOGE("getCompositionType called with an invalid HWC layer");
1239         return HWC2::Composition::Invalid;
1240     }
1241     return mHwcLayers.at(hwcId).compositionType;
1242 }
1243
1244 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1245     if (mHwcLayers.count(hwcId) == 0) {
1246         ALOGE("setClearClientTarget called without a valid HWC layer");
1247         return;
1248     }
1249     mHwcLayers[hwcId].clearClientTarget = clear;
1250 }
1251
1252 bool Layer::getClearClientTarget(int32_t hwcId) const {
1253     if (mHwcLayers.count(hwcId) == 0) {
1254         ALOGE("getClearClientTarget called without a valid HWC layer");
1255         return false;
1256     }
1257     return mHwcLayers.at(hwcId).clearClientTarget;
1258 }
1259 #endif
1260
1261 uint32_t Layer::getProducerStickyTransform() const {
1262     int producerStickyTransform = 0;
1263     int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1264     if (ret != OK) {
1265         ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1266                 strerror(-ret), ret);
1267         return 0;
1268     }
1269     return static_cast<uint32_t>(producerStickyTransform);
1270 }
1271
1272 bool Layer::latchUnsignaledBuffers() {
1273     static bool propertyLoaded = false;
1274     static bool latch = false;
1275     static std::mutex mutex;
1276     std::lock_guard<std::mutex> lock(mutex);
1277     if (!propertyLoaded) {
1278         char value[PROPERTY_VALUE_MAX] = {};
1279         property_get("debug.sf.latch_unsignaled", value, "0");
1280         latch = atoi(value);
1281         propertyLoaded = true;
1282     }
1283     return latch;
1284 }
1285
1286 uint64_t Layer::getHeadFrameNumber() const {
1287     Mutex::Autolock lock(mQueueItemLock);
1288     if (!mQueueItems.empty()) {
1289         return mQueueItems[0].mFrameNumber;
1290     } else {
1291         return mCurrentFrameNumber;
1292     }
1293 }
1294
1295 bool Layer::headFenceHasSignaled() const {
1296 #ifdef USE_HWC2
1297     if (latchUnsignaledBuffers()) {
1298         return true;
1299     }
1300
1301     Mutex::Autolock lock(mQueueItemLock);
1302     if (mQueueItems.empty()) {
1303         return true;
1304     }
1305     if (mQueueItems[0].mIsDroppable) {
1306         // Even though this buffer's fence may not have signaled yet, it could
1307         // be replaced by another buffer before it has a chance to, which means
1308         // that it's possible to get into a situation where a buffer is never
1309         // able to be latched. To avoid this, grab this buffer anyway.
1310         return true;
1311     }
1312     return mQueueItems[0].mFenceTime->getSignalTime() !=
1313             Fence::SIGNAL_TIME_PENDING;
1314 #else
1315     return true;
1316 #endif
1317 }
1318
1319 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1320     if (point->getFrameNumber() <= mCurrentFrameNumber) {
1321         // Don't bother with a SyncPoint, since we've already latched the
1322         // relevant frame
1323         return false;
1324     }
1325
1326     Mutex::Autolock lock(mLocalSyncPointMutex);
1327     mLocalSyncPoints.push_back(point);
1328     return true;
1329 }
1330
1331 void Layer::setFiltering(bool filtering) {
1332     mFiltering = filtering;
1333 }
1334
1335 bool Layer::getFiltering() const {
1336     return mFiltering;
1337 }
1338
1339 // As documented in libhardware header, formats in the range
1340 // 0x100 - 0x1FF are specific to the HAL implementation, and
1341 // are known to have no alpha channel
1342 // TODO: move definition for device-specific range into
1343 // hardware.h, instead of using hard-coded values here.
1344 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1345
1346 bool Layer::getOpacityForFormat(uint32_t format) {
1347     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1348         return true;
1349     }
1350     switch (format) {
1351         case HAL_PIXEL_FORMAT_RGBA_8888:
1352         case HAL_PIXEL_FORMAT_BGRA_8888:
1353         case HAL_PIXEL_FORMAT_RGBA_FP16:
1354         case HAL_PIXEL_FORMAT_RGBA_1010102:
1355             return false;
1356     }
1357     // in all other case, we have no blending (also for unknown formats)
1358     return true;
1359 }
1360
1361 // ----------------------------------------------------------------------------
1362 // local state
1363 // ----------------------------------------------------------------------------
1364
1365 static void boundPoint(vec2* point, const Rect& crop) {
1366     if (point->x < crop.left) {
1367         point->x = crop.left;
1368     }
1369     if (point->x > crop.right) {
1370         point->x = crop.right;
1371     }
1372     if (point->y < crop.top) {
1373         point->y = crop.top;
1374     }
1375     if (point->y > crop.bottom) {
1376         point->y = crop.bottom;
1377     }
1378 }
1379
1380 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1381         bool useIdentityTransform) const
1382 {
1383     const Layer::State& s(getDrawingState());
1384     const Transform hwTransform(hw->getTransform());
1385     const uint32_t hw_h = hw->getHeight();
1386     Rect win = computeBounds();
1387
1388     vec2 lt = vec2(win.left, win.top);
1389     vec2 lb = vec2(win.left, win.bottom);
1390     vec2 rb = vec2(win.right, win.bottom);
1391     vec2 rt = vec2(win.right, win.top);
1392
1393     Transform layerTransform = getTransform();
1394     if (!useIdentityTransform) {
1395         lt = layerTransform.transform(lt);
1396         lb = layerTransform.transform(lb);
1397         rb = layerTransform.transform(rb);
1398         rt = layerTransform.transform(rt);
1399     }
1400
1401     if (!s.finalCrop.isEmpty()) {
1402         boundPoint(&lt, s.finalCrop);
1403         boundPoint(&lb, s.finalCrop);
1404         boundPoint(&rb, s.finalCrop);
1405         boundPoint(&rt, s.finalCrop);
1406     }
1407
1408     Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1409     position[0] = hwTransform.transform(lt);
1410     position[1] = hwTransform.transform(lb);
1411     position[2] = hwTransform.transform(rb);
1412     position[3] = hwTransform.transform(rt);
1413     for (size_t i=0 ; i<4 ; i++) {
1414         position[i].y = hw_h - position[i].y;
1415     }
1416 }
1417
1418 bool Layer::isOpaque(const Layer::State& s) const
1419 {
1420     // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
1421     // layer's opaque flag.
1422     if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
1423         return false;
1424     }
1425
1426     // if the layer has the opaque flag, then we're always opaque,
1427     // otherwise we use the current buffer's format.
1428     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1429 }
1430
1431 bool Layer::isSecure() const
1432 {
1433     const Layer::State& s(mDrawingState);
1434     return (s.flags & layer_state_t::eLayerSecure);
1435 }
1436
1437 bool Layer::isProtected() const
1438 {
1439     const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1440     return (activeBuffer != 0) &&
1441             (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1442 }
1443
1444 bool Layer::isFixedSize() const {
1445     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1446 }
1447
1448 bool Layer::isCropped() const {
1449     return !mCurrentCrop.isEmpty();
1450 }
1451
1452 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1453     return mNeedsFiltering || hw->needsFiltering();
1454 }
1455
1456 void Layer::setVisibleRegion(const Region& visibleRegion) {
1457     // always called from main thread
1458     this->visibleRegion = visibleRegion;
1459 }
1460
1461 void Layer::setCoveredRegion(const Region& coveredRegion) {
1462     // always called from main thread
1463     this->coveredRegion = coveredRegion;
1464 }
1465
1466 void Layer::setVisibleNonTransparentRegion(const Region&
1467         setVisibleNonTransparentRegion) {
1468     // always called from main thread
1469     this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1470 }
1471
1472 // ----------------------------------------------------------------------------
1473 // transaction
1474 // ----------------------------------------------------------------------------
1475
1476 void Layer::pushPendingState() {
1477     if (!mCurrentState.modified) {
1478         return;
1479     }
1480
1481     // If this transaction is waiting on the receipt of a frame, generate a sync
1482     // point and send it to the remote layer.
1483     if (mCurrentState.barrierLayer != nullptr) {
1484         sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1485         if (barrierLayer == nullptr) {
1486             ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1487             // If we can't promote the layer we are intended to wait on,
1488             // then it is expired or otherwise invalid. Allow this transaction
1489             // to be applied as per normal (no synchronization).
1490             mCurrentState.barrierLayer = nullptr;
1491         } else {
1492             auto syncPoint = std::make_shared<SyncPoint>(
1493                     mCurrentState.frameNumber);
1494             if (barrierLayer->addSyncPoint(syncPoint)) {
1495                 mRemoteSyncPoints.push_back(std::move(syncPoint));
1496             } else {
1497                 // We already missed the frame we're supposed to synchronize
1498                 // on, so go ahead and apply the state update
1499                 mCurrentState.barrierLayer = nullptr;
1500             }
1501         }
1502
1503         // Wake us up to check if the frame has been received
1504         setTransactionFlags(eTransactionNeeded);
1505         mFlinger->setTransactionFlags(eTraversalNeeded);
1506     }
1507     mPendingStates.push_back(mCurrentState);
1508     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1509 }
1510
1511 void Layer::popPendingState(State* stateToCommit) {
1512     auto oldFlags = stateToCommit->flags;
1513     *stateToCommit = mPendingStates[0];
1514     stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1515             (stateToCommit->flags & stateToCommit->mask);
1516
1517     mPendingStates.removeAt(0);
1518     ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1519 }
1520
1521 bool Layer::applyPendingStates(State* stateToCommit) {
1522     bool stateUpdateAvailable = false;
1523     while (!mPendingStates.empty()) {
1524         if (mPendingStates[0].barrierLayer != nullptr) {
1525             if (mRemoteSyncPoints.empty()) {
1526                 // If we don't have a sync point for this, apply it anyway. It
1527                 // will be visually wrong, but it should keep us from getting
1528                 // into too much trouble.
1529                 ALOGE("[%s] No local sync point found", mName.string());
1530                 popPendingState(stateToCommit);
1531                 stateUpdateAvailable = true;
1532                 continue;
1533             }
1534
1535             if (mRemoteSyncPoints.front()->getFrameNumber() !=
1536                     mPendingStates[0].frameNumber) {
1537                 ALOGE("[%s] Unexpected sync point frame number found",
1538                         mName.string());
1539
1540                 // Signal our end of the sync point and then dispose of it
1541                 mRemoteSyncPoints.front()->setTransactionApplied();
1542                 mRemoteSyncPoints.pop_front();
1543                 continue;
1544             }
1545
1546             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1547                 // Apply the state update
1548                 popPendingState(stateToCommit);
1549                 stateUpdateAvailable = true;
1550
1551                 // Signal our end of the sync point and then dispose of it
1552                 mRemoteSyncPoints.front()->setTransactionApplied();
1553                 mRemoteSyncPoints.pop_front();
1554             } else {
1555                 break;
1556             }
1557         } else {
1558             popPendingState(stateToCommit);
1559             stateUpdateAvailable = true;
1560         }
1561     }
1562
1563     // If we still have pending updates, wake SurfaceFlinger back up and point
1564     // it at this layer so we can process them
1565     if (!mPendingStates.empty()) {
1566         setTransactionFlags(eTransactionNeeded);
1567         mFlinger->setTransactionFlags(eTraversalNeeded);
1568     }
1569
1570     mCurrentState.modified = false;
1571     return stateUpdateAvailable;
1572 }
1573
1574 void Layer::notifyAvailableFrames() {
1575     auto headFrameNumber = getHeadFrameNumber();
1576     bool headFenceSignaled = headFenceHasSignaled();
1577     Mutex::Autolock lock(mLocalSyncPointMutex);
1578     for (auto& point : mLocalSyncPoints) {
1579         if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1580             point->setFrameAvailable();
1581         }
1582     }
1583 }
1584
1585 uint32_t Layer::doTransaction(uint32_t flags) {
1586     ATRACE_CALL();
1587
1588     pushPendingState();
1589     Layer::State c = getCurrentState();
1590     if (!applyPendingStates(&c)) {
1591         return 0;
1592     }
1593
1594     const Layer::State& s(getDrawingState());
1595
1596     const bool sizeChanged = (c.requested.w != s.requested.w) ||
1597                              (c.requested.h != s.requested.h);
1598
1599     if (sizeChanged) {
1600         // the size changed, we need to ask our client to request a new buffer
1601         ALOGD_IF(DEBUG_RESIZE,
1602                 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1603                 "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1604                 "            requested={ wh={%4u,%4u} }}\n"
1605                 "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1606                 "            requested={ wh={%4u,%4u} }}\n",
1607                 this, getName().string(), mCurrentTransform,
1608                 getEffectiveScalingMode(),
1609                 c.active.w, c.active.h,
1610                 c.crop.left,
1611                 c.crop.top,
1612                 c.crop.right,
1613                 c.crop.bottom,
1614                 c.crop.getWidth(),
1615                 c.crop.getHeight(),
1616                 c.requested.w, c.requested.h,
1617                 s.active.w, s.active.h,
1618                 s.crop.left,
1619                 s.crop.top,
1620                 s.crop.right,
1621                 s.crop.bottom,
1622                 s.crop.getWidth(),
1623                 s.crop.getHeight(),
1624                 s.requested.w, s.requested.h);
1625
1626         // record the new size, form this point on, when the client request
1627         // a buffer, it'll get the new size.
1628         mSurfaceFlingerConsumer->setDefaultBufferSize(
1629                 c.requested.w, c.requested.h);
1630     }
1631
1632     const bool resizePending = (c.requested.w != c.active.w) ||
1633             (c.requested.h != c.active.h);
1634     if (!isFixedSize()) {
1635         if (resizePending && mSidebandStream == NULL) {
1636             // don't let Layer::doTransaction update the drawing state
1637             // if we have a pending resize, unless we are in fixed-size mode.
1638             // the drawing state will be updated only once we receive a buffer
1639             // with the correct size.
1640             //
1641             // in particular, we want to make sure the clip (which is part
1642             // of the geometry state) is latched together with the size but is
1643             // latched immediately when no resizing is involved.
1644             //
1645             // If a sideband stream is attached, however, we want to skip this
1646             // optimization so that transactions aren't missed when a buffer
1647             // never arrives
1648
1649             flags |= eDontUpdateGeometryState;
1650         }
1651     }
1652
1653     // Here we apply various requested geometry states, depending on our
1654     // latching configuration. See Layer.h for a detailed discussion of
1655     // how geometry latching is controlled.
1656     if (!(flags & eDontUpdateGeometryState)) {
1657         Layer::State& editCurrentState(getCurrentState());
1658
1659         // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1660         // mode, which causes attributes which normally latch regardless of scaling mode,
1661         // to be delayed. We copy the requested state to the active state making sure
1662         // to respect these rules (again see Layer.h for a detailed discussion).
1663         //
1664         // There is an awkward asymmetry in the handling of the crop states in the position
1665         // states, as can be seen below. Largely this arises from position and transform
1666         // being stored in the same data structure while having different latching rules.
1667         // b/38182305
1668         //
1669         // Careful that "c" and editCurrentState may not begin as equivalent due to
1670         // applyPendingStates in the presence of deferred transactions.
1671         if (mFreezeGeometryUpdates) {
1672             float tx = c.active.transform.tx();
1673             float ty = c.active.transform.ty();
1674             c.active = c.requested;
1675             c.active.transform.set(tx, ty);
1676             editCurrentState.active = c.active;
1677         } else {
1678             editCurrentState.active = editCurrentState.requested;
1679             c.active = c.requested;
1680         }
1681     }
1682
1683     if (s.active != c.active) {
1684         // invalidate and recompute the visible regions if needed
1685         flags |= Layer::eVisibleRegion;
1686     }
1687
1688     if (c.sequence != s.sequence) {
1689         // invalidate and recompute the visible regions if needed
1690         flags |= eVisibleRegion;
1691         this->contentDirty = true;
1692
1693         // we may use linear filtering, if the matrix scales us
1694         const uint8_t type = c.active.transform.getType();
1695         mNeedsFiltering = (!c.active.transform.preserveRects() ||
1696                 (type >= Transform::SCALE));
1697     }
1698
1699     // If the layer is hidden, signal and clear out all local sync points so
1700     // that transactions for layers depending on this layer's frames becoming
1701     // visible are not blocked
1702     if (c.flags & layer_state_t::eLayerHidden) {
1703         clearSyncPoints();
1704     }
1705
1706     // Commit the transaction
1707     commitTransaction(c);
1708     return flags;
1709 }
1710
1711 void Layer::commitTransaction(const State& stateToCommit) {
1712     mDrawingState = stateToCommit;
1713 }
1714
1715 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1716     return android_atomic_and(~flags, &mTransactionFlags) & flags;
1717 }
1718
1719 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1720     return android_atomic_or(flags, &mTransactionFlags);
1721 }
1722
1723 bool Layer::setPosition(float x, float y, bool immediate) {
1724     if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1725         return false;
1726     mCurrentState.sequence++;
1727
1728     // We update the requested and active position simultaneously because
1729     // we want to apply the position portion of the transform matrix immediately,
1730     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1731     mCurrentState.requested.transform.set(x, y);
1732     if (immediate && !mFreezeGeometryUpdates) {
1733         // Here we directly update the active state
1734         // unlike other setters, because we store it within
1735         // the transform, but use different latching rules.
1736         // b/38182305
1737         mCurrentState.active.transform.set(x, y);
1738     }
1739     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1740
1741     mCurrentState.modified = true;
1742     setTransactionFlags(eTransactionNeeded);
1743     return true;
1744 }
1745
1746 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1747     ssize_t idx = mCurrentChildren.indexOf(childLayer);
1748     if (idx < 0) {
1749         return false;
1750     }
1751     if (childLayer->setLayer(z)) {
1752         mCurrentChildren.removeAt(idx);
1753         mCurrentChildren.add(childLayer);
1754     }
1755     return true;
1756 }
1757
1758 bool Layer::setLayer(int32_t z) {
1759     if (mCurrentState.z == z)
1760         return false;
1761     mCurrentState.sequence++;
1762     mCurrentState.z = z;
1763     mCurrentState.modified = true;
1764
1765     // Discard all relative layering.
1766     if (mCurrentState.zOrderRelativeOf != nullptr) {
1767         sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1768         if (strongRelative != nullptr) {
1769             strongRelative->removeZOrderRelative(this);
1770         }
1771         mCurrentState.zOrderRelativeOf = nullptr;
1772     }
1773     setTransactionFlags(eTransactionNeeded);
1774     return true;
1775 }
1776
1777 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1778     mCurrentState.zOrderRelatives.remove(relative);
1779     mCurrentState.sequence++;
1780     mCurrentState.modified = true;
1781     setTransactionFlags(eTransactionNeeded);
1782 }
1783
1784 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1785     mCurrentState.zOrderRelatives.add(relative);
1786     mCurrentState.modified = true;
1787     mCurrentState.sequence++;
1788     setTransactionFlags(eTransactionNeeded);
1789 }
1790
1791 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1792     sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1793     if (handle == nullptr) {
1794         return false;
1795     }
1796     sp<Layer> relative = handle->owner.promote();
1797     if (relative == nullptr) {
1798         return false;
1799     }
1800
1801     mCurrentState.sequence++;
1802     mCurrentState.modified = true;
1803     mCurrentState.z = z;
1804
1805     mCurrentState.zOrderRelativeOf = relative;
1806     relative->addZOrderRelative(this);
1807
1808     setTransactionFlags(eTransactionNeeded);
1809
1810     return true;
1811 }
1812
1813 bool Layer::setSize(uint32_t w, uint32_t h) {
1814     if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1815         return false;
1816     mCurrentState.requested.w = w;
1817     mCurrentState.requested.h = h;
1818     mCurrentState.modified = true;
1819     setTransactionFlags(eTransactionNeeded);
1820     return true;
1821 }
1822 #ifdef USE_HWC2
1823 bool Layer::setAlpha(float alpha) {
1824 #else
1825 bool Layer::setAlpha(uint8_t alpha) {
1826 #endif
1827     if (mCurrentState.alpha == alpha)
1828         return false;
1829     mCurrentState.sequence++;
1830     mCurrentState.alpha = alpha;
1831     mCurrentState.modified = true;
1832     setTransactionFlags(eTransactionNeeded);
1833     return true;
1834 }
1835 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1836     mCurrentState.sequence++;
1837     mCurrentState.requested.transform.set(
1838             matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1839     mCurrentState.modified = true;
1840     setTransactionFlags(eTransactionNeeded);
1841     return true;
1842 }
1843 bool Layer::setTransparentRegionHint(const Region& transparent) {
1844     mCurrentState.requestedTransparentRegion = transparent;
1845     mCurrentState.modified = true;
1846     setTransactionFlags(eTransactionNeeded);
1847     return true;
1848 }
1849 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1850     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1851     if (mCurrentState.flags == newFlags)
1852         return false;
1853     mCurrentState.sequence++;
1854     mCurrentState.flags = newFlags;
1855     mCurrentState.mask = mask;
1856     mCurrentState.modified = true;
1857     setTransactionFlags(eTransactionNeeded);
1858     return true;
1859 }
1860
1861 bool Layer::setCrop(const Rect& crop, bool immediate) {
1862     if (mCurrentState.requestedCrop == crop)
1863         return false;
1864     mCurrentState.sequence++;
1865     mCurrentState.requestedCrop = crop;
1866     if (immediate && !mFreezeGeometryUpdates) {
1867         mCurrentState.crop = crop;
1868     }
1869     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1870
1871     mCurrentState.modified = true;
1872     setTransactionFlags(eTransactionNeeded);
1873     return true;
1874 }
1875
1876 bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1877     if (mCurrentState.requestedFinalCrop == crop)
1878         return false;
1879     mCurrentState.sequence++;
1880     mCurrentState.requestedFinalCrop = crop;
1881     if (immediate && !mFreezeGeometryUpdates) {
1882         mCurrentState.finalCrop = crop;
1883     }
1884     mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1885
1886     mCurrentState.modified = true;
1887     setTransactionFlags(eTransactionNeeded);
1888     return true;
1889 }
1890
1891 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1892     if (scalingMode == mOverrideScalingMode)
1893         return false;
1894     mOverrideScalingMode = scalingMode;
1895     setTransactionFlags(eTransactionNeeded);
1896     return true;
1897 }
1898
1899 void Layer::setInfo(uint32_t type, uint32_t appId) {
1900   mCurrentState.appId = appId;
1901   mCurrentState.type = type;
1902   mCurrentState.modified = true;
1903   setTransactionFlags(eTransactionNeeded);
1904 }
1905
1906 uint32_t Layer::getEffectiveScalingMode() const {
1907     if (mOverrideScalingMode >= 0) {
1908       return mOverrideScalingMode;
1909     }
1910     return mCurrentScalingMode;
1911 }
1912
1913 bool Layer::setLayerStack(uint32_t layerStack) {
1914     if (mCurrentState.layerStack == layerStack)
1915         return false;
1916     mCurrentState.sequence++;
1917     mCurrentState.layerStack = layerStack;
1918     mCurrentState.modified = true;
1919     setTransactionFlags(eTransactionNeeded);
1920     return true;
1921 }
1922
1923 bool Layer::setDataSpace(android_dataspace dataSpace) {
1924     if (mCurrentState.dataSpace == dataSpace)
1925         return false;
1926     mCurrentState.sequence++;
1927     mCurrentState.dataSpace = dataSpace;
1928     mCurrentState.modified = true;
1929     setTransactionFlags(eTransactionNeeded);
1930     return true;
1931 }
1932
1933 android_dataspace Layer::getDataSpace() const {
1934     return mCurrentState.dataSpace;
1935 }
1936
1937 uint32_t Layer::getLayerStack() const {
1938     auto p = mDrawingParent.promote();
1939     if (p == nullptr) {
1940         return getDrawingState().layerStack;
1941     }
1942     return p->getLayerStack();
1943 }
1944
1945 void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
1946         uint64_t frameNumber) {
1947     mCurrentState.barrierLayer = barrierLayer;
1948     mCurrentState.frameNumber = frameNumber;
1949     // We don't set eTransactionNeeded, because just receiving a deferral
1950     // request without any other state updates shouldn't actually induce a delay
1951     mCurrentState.modified = true;
1952     pushPendingState();
1953     mCurrentState.barrierLayer = nullptr;
1954     mCurrentState.frameNumber = 0;
1955     mCurrentState.modified = false;
1956 }
1957
1958 void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1959         uint64_t frameNumber) {
1960     sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1961     deferTransactionUntil(handle->owner.promote(), frameNumber);
1962 }
1963
1964 void Layer::useSurfaceDamage() {
1965     if (mFlinger->mForceFullDamage) {
1966         surfaceDamageRegion = Region::INVALID_REGION;
1967     } else {
1968         surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1969     }
1970 }
1971
1972 void Layer::useEmptyDamage() {
1973     surfaceDamageRegion.clear();
1974 }
1975
1976 // ----------------------------------------------------------------------------
1977 // pageflip handling...
1978 // ----------------------------------------------------------------------------
1979
1980 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1981     if (mSidebandStreamChanged || mAutoRefresh) {
1982         return true;
1983     }
1984
1985     Mutex::Autolock lock(mQueueItemLock);
1986     if (mQueueItems.empty()) {
1987         return false;
1988     }
1989     auto timestamp = mQueueItems[0].mTimestamp;
1990     nsecs_t expectedPresent =
1991             mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1992
1993     // Ignore timestamps more than a second in the future
1994     bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1995     ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1996             "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1997             expectedPresent);
1998
1999     bool isDue = timestamp < expectedPresent;
2000     return isDue || !isPlausible;
2001 }
2002
2003 bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2004     if (mBufferLatched) {
2005         Mutex::Autolock lock(mFrameEventHistoryMutex);
2006         mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2007     }
2008     mRefreshPending = false;
2009     return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
2010 }
2011
2012 bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
2013         const std::shared_ptr<FenceTime>& presentFence,
2014         const CompositorTiming& compositorTiming) {
2015     // mFrameLatencyNeeded is true when a new frame was latched for the
2016     // composition.
2017     if (!mFrameLatencyNeeded)
2018         return false;
2019
2020     // Update mFrameEventHistory.
2021     {
2022         Mutex::Autolock lock(mFrameEventHistoryMutex);
2023         mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
2024                 glDoneFence, presentFence, compositorTiming);
2025     }
2026
2027     // Update mFrameTracker.
2028     nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2029     mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2030
2031     std::shared_ptr<FenceTime> frameReadyFence =
2032             mSurfaceFlingerConsumer->getCurrentFenceTime();
2033     if (frameReadyFence->isValid()) {
2034         mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
2035     } else {
2036         // There was no fence for this frame, so assume that it was ready
2037         // to be presented at the desired present time.
2038         mFrameTracker.setFrameReadyTime(desiredPresentTime);
2039     }
2040
2041     if (presentFence->isValid()) {
2042         mFrameTracker.setActualPresentFence(
2043                 std::shared_ptr<FenceTime>(presentFence));
2044     } else {
2045         // The HWC doesn't support present fences, so use the refresh
2046         // timestamp instead.
2047         mFrameTracker.setActualPresentTime(
2048             mFlinger->getHwComposer().getRefreshTimestamp(
2049                 HWC_DISPLAY_PRIMARY));
2050     }
2051
2052     mFrameTracker.advanceFrame();
2053     mFrameLatencyNeeded = false;
2054     return true;
2055 }
2056
2057 #ifdef USE_HWC2
2058 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2059     if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2060         return;
2061     }
2062
2063     auto releaseFenceTime = std::make_shared<FenceTime>(
2064             mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2065     mReleaseTimeline.updateSignalTimes();
2066     mReleaseTimeline.push(releaseFenceTime);
2067
2068     Mutex::Autolock lock(mFrameEventHistoryMutex);
2069     if (mPreviousFrameNumber != 0) {
2070         mFrameEventHistory.addRelease(mPreviousFrameNumber,
2071                 dequeueReadyTime, std::move(releaseFenceTime));
2072     }
2073 }
2074 #endif
2075
2076 bool Layer::isHiddenByPolicy() const {
2077     const Layer::State& s(mDrawingState);
2078     const auto& parent = mDrawingParent.promote();
2079     if (parent != nullptr && parent->isHiddenByPolicy()) {
2080         return true;
2081     }
2082     return s.flags & layer_state_t::eLayerHidden;
2083 }
2084
2085 bool Layer::isVisible() const {
2086 #ifdef USE_HWC2
2087     return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2088             && (mActiveBuffer != NULL || mSidebandStream != NULL);
2089 #else
2090     return !(isHiddenByPolicy()) && getAlpha()
2091             && (mActiveBuffer != NULL || mSidebandStream != NULL);
2092 #endif
2093 }
2094
2095 bool Layer::allTransactionsSignaled() {
2096     auto headFrameNumber = getHeadFrameNumber();
2097     bool matchingFramesFound = false;
2098     bool allTransactionsApplied = true;
2099     Mutex::Autolock lock(mLocalSyncPointMutex);
2100
2101     for (auto& point : mLocalSyncPoints) {
2102         if (point->getFrameNumber() > headFrameNumber) {
2103             break;
2104         }
2105         matchingFramesFound = true;
2106
2107         if (!point->frameIsAvailable()) {
2108            // We haven't notified the remote layer that the frame for
2109            // this point is available yet. Notify it now, and then
2110            // abort this attempt to latch.
2111            point->setFrameAvailable();
2112            allTransactionsApplied = false;
2113            break;
2114         }
2115
2116         allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2117     }
2118     return !matchingFramesFound || allTransactionsApplied;
2119 }
2120
2121 Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2122 {
2123     ATRACE_CALL();
2124
2125     if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2126         // mSidebandStreamChanged was true
2127         mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2128         if (mSidebandStream != NULL) {
2129             setTransactionFlags(eTransactionNeeded);
2130             mFlinger->setTransactionFlags(eTraversalNeeded);
2131         }
2132         recomputeVisibleRegions = true;
2133
2134         const State& s(getDrawingState());
2135         return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2136     }
2137
2138     Region outDirtyRegion;
2139     if (mQueuedFrames <= 0 && !mAutoRefresh) {
2140         return outDirtyRegion;
2141     }
2142
2143     // if we've already called updateTexImage() without going through
2144     // a composition step, we have to skip this layer at this point
2145     // because we cannot call updateTeximage() without a corresponding
2146     // compositionComplete() call.
2147     // we'll trigger an update in onPreComposition().
2148     if (mRefreshPending) {
2149         return outDirtyRegion;
2150     }
2151
2152     // If the head buffer's acquire fence hasn't signaled yet, return and
2153     // try again later
2154     if (!headFenceHasSignaled()) {
2155         mFlinger->signalLayerUpdate();
2156         return outDirtyRegion;
2157     }
2158
2159     // Capture the old state of the layer for comparisons later
2160     const State& s(getDrawingState());
2161     const bool oldOpacity = isOpaque(s);
2162     sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2163
2164     if (!allTransactionsSignaled()) {
2165         mFlinger->signalLayerUpdate();
2166         return outDirtyRegion;
2167     }
2168
2169     // This boolean is used to make sure that SurfaceFlinger's shadow copy
2170     // of the buffer queue isn't modified when the buffer queue is returning
2171     // BufferItem's that weren't actually queued. This can happen in shared
2172     // buffer mode.
2173     bool queuedBuffer = false;
2174     LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2175                     getProducerStickyTransform() != 0, mName.string(),
2176                     mOverrideScalingMode, mFreezeGeometryUpdates);
2177     status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2178             mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2179             mLastFrameNumberReceived);
2180     if (updateResult == BufferQueue::PRESENT_LATER) {
2181         // Producer doesn't want buffer to be displayed yet.  Signal a
2182         // layer update so we check again at the next opportunity.
2183         mFlinger->signalLayerUpdate();
2184         return outDirtyRegion;
2185     } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2186         // If the buffer has been rejected, remove it from the shadow queue
2187         // and return early
2188         if (queuedBuffer) {
2189             Mutex::Autolock lock(mQueueItemLock);
2190             mQueueItems.removeAt(0);
2191             android_atomic_dec(&mQueuedFrames);
2192         }
2193         return outDirtyRegion;
2194     } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2195         // This can occur if something goes wrong when trying to create the
2196         // EGLImage for this buffer. If this happens, the buffer has already
2197         // been released, so we need to clean up the queue and bug out
2198         // early.
2199         if (queuedBuffer) {
2200             Mutex::Autolock lock(mQueueItemLock);
2201             mQueueItems.clear();
2202             android_atomic_and(0, &mQueuedFrames);
2203         }
2204
2205         // Once we have hit this state, the shadow queue may no longer
2206         // correctly reflect the incoming BufferQueue's contents, so even if
2207         // updateTexImage starts working, the only safe course of action is
2208         // to continue to ignore updates.
2209         mUpdateTexImageFailed = true;
2210
2211         return outDirtyRegion;
2212     }
2213
2214     if (queuedBuffer) {
2215         // Autolock scope
2216         auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2217
2218         Mutex::Autolock lock(mQueueItemLock);
2219
2220         // Remove any stale buffers that have been dropped during
2221         // updateTexImage
2222         while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2223             mQueueItems.removeAt(0);
2224             android_atomic_dec(&mQueuedFrames);
2225         }
2226
2227         mQueueItems.removeAt(0);
2228     }
2229
2230
2231     // Decrement the queued-frames count.  Signal another event if we
2232     // have more frames pending.
2233     if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2234             || mAutoRefresh) {
2235         mFlinger->signalLayerUpdate();
2236     }
2237
2238     // update the active buffer
2239     mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2240             &mActiveBufferSlot);
2241     if (mActiveBuffer == NULL) {
2242         // this can only happen if the very first buffer was rejected.
2243         return outDirtyRegion;
2244     }
2245
2246     mBufferLatched = true;
2247     mPreviousFrameNumber = mCurrentFrameNumber;
2248     mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2249
2250     {
2251         Mutex::Autolock lock(mFrameEventHistoryMutex);
2252         mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2253 #ifndef USE_HWC2
2254         auto releaseFenceTime = std::make_shared<FenceTime>(
2255                 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2256         mReleaseTimeline.updateSignalTimes();
2257         mReleaseTimeline.push(releaseFenceTime);
2258         if (mPreviousFrameNumber != 0) {
2259             mFrameEventHistory.addRelease(mPreviousFrameNumber,
2260                     latchTime, std::move(releaseFenceTime));
2261         }
2262 #endif
2263     }
2264
2265     mRefreshPending = true;
2266     mFrameLatencyNeeded = true;
2267     if (oldActiveBuffer == NULL) {
2268          // the first time we receive a buffer, we need to trigger a
2269          // geometry invalidation.
2270         recomputeVisibleRegions = true;
2271      }
2272
2273     setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2274
2275     Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2276     const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2277     const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2278     if ((crop != mCurrentCrop) ||
2279         (transform != mCurrentTransform) ||
2280         (scalingMode != mCurrentScalingMode))
2281     {
2282         mCurrentCrop = crop;
2283         mCurrentTransform = transform;
2284         mCurrentScalingMode = scalingMode;
2285         recomputeVisibleRegions = true;
2286     }
2287
2288     if (oldActiveBuffer != NULL) {
2289         uint32_t bufWidth  = mActiveBuffer->getWidth();
2290         uint32_t bufHeight = mActiveBuffer->getHeight();
2291         if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2292             bufHeight != uint32_t(oldActiveBuffer->height)) {
2293             recomputeVisibleRegions = true;
2294         }
2295     }
2296
2297     mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2298     if (oldOpacity != isOpaque(s)) {
2299         recomputeVisibleRegions = true;
2300     }
2301
2302     // Remove any sync points corresponding to the buffer which was just
2303     // latched
2304     {
2305         Mutex::Autolock lock(mLocalSyncPointMutex);
2306         auto point = mLocalSyncPoints.begin();
2307         while (point != mLocalSyncPoints.end()) {
2308             if (!(*point)->frameIsAvailable() ||
2309                     !(*point)->transactionIsApplied()) {
2310                 // This sync point must have been added since we started
2311                 // latching. Don't drop it yet.
2312                 ++point;
2313                 continue;
2314             }
2315
2316             if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2317                 point = mLocalSyncPoints.erase(point);
2318             } else {
2319                 ++point;
2320             }
2321         }
2322     }
2323
2324     // FIXME: postedRegion should be dirty & bounds
2325     Region dirtyRegion(Rect(s.active.w, s.active.h));
2326
2327     // transform the dirty region to window-manager space
2328     outDirtyRegion = (getTransform().transform(dirtyRegion));
2329
2330     return outDirtyRegion;
2331 }
2332
2333 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2334 {
2335     // TODO: should we do something special if mSecure is set?
2336     if (mProtectedByApp) {
2337         // need a hardware-protected path to external video sink
2338         usage |= GraphicBuffer::USAGE_PROTECTED;
2339     }
2340     if (mPotentialCursor) {
2341         usage |= GraphicBuffer::USAGE_CURSOR;
2342     }
2343     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2344     return usage;
2345 }
2346
2347 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2348     uint32_t orientation = 0;
2349     if (!mFlinger->mDebugDisableTransformHint) {
2350         // The transform hint is used to improve performance, but we can
2351         // only have a single transform hint, it cannot
2352         // apply to all displays.
2353         const Transform& planeTransform(hw->getTransform());
2354         orientation = planeTransform.getOrientation();
2355         if (orientation & Transform::ROT_INVALID) {
2356             orientation = 0;
2357         }
2358     }
2359     mSurfaceFlingerConsumer->setTransformHint(orientation);
2360 }
2361
2362 // ----------------------------------------------------------------------------
2363 // debugging
2364 // ----------------------------------------------------------------------------
2365
2366 void Layer::dump(String8& result, Colorizer& colorizer) const
2367 {
2368     const Layer::State& s(getDrawingState());
2369
2370     colorizer.colorize(result, Colorizer::GREEN);
2371     result.appendFormat(
2372             "+ %s %p (%s)\n",
2373             getTypeId(), this, getName().string());
2374     colorizer.reset(result);
2375
2376     s.activeTransparentRegion.dump(result, "transparentRegion");
2377     visibleRegion.dump(result, "visibleRegion");
2378     surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2379     sp<Client> client(mClientRef.promote());
2380     PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2381     const sp<GraphicBuffer>& buffer(getActiveBuffer());
2382     if (buffer != NULL) {
2383         pf = buffer->getPixelFormat();
2384     }
2385
2386     result.appendFormat(            "      "
2387             "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2388             "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2389             "isOpaque=%1d, invalidate=%1d, "
2390             "dataspace=%s, pixelformat=%s "
2391 #ifdef USE_HWC2
2392             "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2393 #else
2394             "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2395 #endif
2396             "      client=%p\n",
2397             getLayerStack(), s.z,
2398             s.active.transform.tx(), s.active.transform.ty(),
2399             s.active.w, s.active.h,
2400             s.crop.left, s.crop.top,
2401             s.crop.right, s.crop.bottom,
2402             s.finalCrop.left, s.finalCrop.top,
2403             s.finalCrop.right, s.finalCrop.bottom,
2404             isOpaque(s), contentDirty,
2405             dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
2406             s.alpha, s.flags,
2407             s.active.transform[0][0], s.active.transform[0][1],
2408             s.active.transform[1][0], s.active.transform[1][1],
2409             client.get());
2410
2411     sp<const GraphicBuffer> buf0(mActiveBuffer);
2412     uint32_t w0=0, h0=0, s0=0, f0=0;
2413     if (buf0 != 0) {
2414         w0 = buf0->getWidth();
2415         h0 = buf0->getHeight();
2416         s0 = buf0->getStride();
2417         f0 = buf0->format;
2418     }
2419     result.appendFormat(
2420             "      "
2421             "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2422             " queued-frames=%d, mRefreshPending=%d\n",
2423             mFormat, w0, h0, s0,f0,
2424             mQueuedFrames, mRefreshPending);
2425
2426     if (mSurfaceFlingerConsumer != 0) {
2427         mSurfaceFlingerConsumer->dumpState(result, "            ");
2428     }
2429 }
2430
2431 #ifdef USE_HWC2
2432 void Layer::miniDumpHeader(String8& result) {
2433     result.append("----------------------------------------");
2434     result.append("---------------------------------------\n");
2435     result.append(" Layer name\n");
2436     result.append("           Z | ");
2437     result.append(" Comp Type | ");
2438     result.append("  Disp Frame (LTRB) | ");
2439     result.append("         Source Crop (LTRB)\n");
2440     result.append("----------------------------------------");
2441     result.append("---------------------------------------\n");
2442 }
2443
2444 void Layer::miniDump(String8& result, int32_t hwcId) const {
2445     if (mHwcLayers.count(hwcId) == 0) {
2446         return;
2447     }
2448
2449     String8 name;
2450     if (mName.length() > 77) {
2451         std::string shortened;
2452         shortened.append(mName.string(), 36);
2453         shortened.append("[...]");
2454         shortened.append(mName.string() + (mName.length() - 36), 36);
2455         name = shortened.c_str();
2456     } else {
2457         name = mName;
2458     }
2459
2460     result.appendFormat(" %s\n", name.string());
2461
2462     const Layer::State& layerState(getDrawingState());
2463     const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2464     result.appendFormat("  %10u | ", layerState.z);
2465     result.appendFormat("%10s | ",
2466             to_string(getCompositionType(hwcId)).c_str());
2467     const Rect& frame = hwcInfo.displayFrame;
2468     result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2469             frame.right, frame.bottom);
2470     const FloatRect& crop = hwcInfo.sourceCrop;
2471     result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2472             crop.right, crop.bottom);
2473
2474     result.append("- - - - - - - - - - - - - - - - - - - - ");
2475     result.append("- - - - - - - - - - - - - - - - - - - -\n");
2476 }
2477 #endif
2478
2479 void Layer::dumpFrameStats(String8& result) const {
2480     mFrameTracker.dumpStats(result);
2481 }
2482
2483 void Layer::clearFrameStats() {
2484     mFrameTracker.clearStats();
2485 }
2486
2487 void Layer::logFrameStats() {
2488     mFrameTracker.logAndResetStats(mName);
2489 }
2490
2491 void Layer::getFrameStats(FrameStats* outStats) const {
2492     mFrameTracker.getStats(outStats);
2493 }
2494
2495 void Layer::dumpFrameEvents(String8& result) {
2496     result.appendFormat("- Layer %s (%s, %p)\n",
2497             getName().string(), getTypeId(), this);
2498     Mutex::Autolock lock(mFrameEventHistoryMutex);
2499     mFrameEventHistory.checkFencesForCompletion();
2500     mFrameEventHistory.dump(result);
2501 }
2502
2503 void Layer::onDisconnect() {
2504     Mutex::Autolock lock(mFrameEventHistoryMutex);
2505     mFrameEventHistory.onDisconnect();
2506 }
2507
2508 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2509         FrameEventHistoryDelta *outDelta) {
2510     Mutex::Autolock lock(mFrameEventHistoryMutex);
2511     if (newTimestamps) {
2512         // If there are any unsignaled fences in the aquire timeline at this
2513         // point, the previously queued frame hasn't been latched yet. Go ahead
2514         // and try to get the signal time here so the syscall is taken out of
2515         // the main thread's critical path.
2516         mAcquireTimeline.updateSignalTimes();
2517         // Push the new fence after updating since it's likely still pending.
2518         mAcquireTimeline.push(newTimestamps->acquireFence);
2519         mFrameEventHistory.addQueue(*newTimestamps);
2520     }
2521
2522     if (outDelta) {
2523         mFrameEventHistory.getAndResetDelta(outDelta);
2524     }
2525 }
2526
2527 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2528         bool forceFlush) {
2529     std::vector<OccupancyTracker::Segment> history;
2530     status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2531             &history);
2532     if (result != NO_ERROR) {
2533         ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2534                 result);
2535         return {};
2536     }
2537     return history;
2538 }
2539
2540 bool Layer::getTransformToDisplayInverse() const {
2541     return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2542 }
2543
2544 size_t Layer::getChildrenCount() const {
2545     size_t count = 0;
2546     for (const sp<Layer>& child : mCurrentChildren) {
2547         count += 1 + child->getChildrenCount();
2548     }
2549     return count;
2550 }
2551
2552 void Layer::addChild(const sp<Layer>& layer) {
2553     mCurrentChildren.add(layer);
2554     layer->setParent(this);
2555 }
2556
2557 ssize_t Layer::removeChild(const sp<Layer>& layer) {
2558     layer->setParent(nullptr);
2559     return mCurrentChildren.remove(layer);
2560 }
2561
2562 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2563     sp<Handle> handle = nullptr;
2564     sp<Layer> newParent = nullptr;
2565     if (newParentHandle == nullptr) {
2566         return false;
2567     }
2568     handle = static_cast<Handle*>(newParentHandle.get());
2569     newParent = handle->owner.promote();
2570     if (newParent == nullptr) {
2571         ALOGE("Unable to promote Layer handle");
2572         return false;
2573     }
2574
2575     for (const sp<Layer>& child : mCurrentChildren) {
2576         newParent->addChild(child);
2577
2578         sp<Client> client(child->mClientRef.promote());
2579         if (client != nullptr) {
2580             client->setParentLayer(newParent);
2581         }
2582     }
2583     mCurrentChildren.clear();
2584
2585     return true;
2586 }
2587
2588 bool Layer::detachChildren() {
2589     traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
2590         if (child == this) {
2591             return;
2592         }
2593
2594         sp<Client> client(child->mClientRef.promote());
2595         if (client != nullptr) {
2596             client->detachLayer(child);
2597         }
2598     });
2599
2600     return true;
2601 }
2602
2603 void Layer::setParent(const sp<Layer>& layer) {
2604     mCurrentParent = layer;
2605 }
2606
2607 void Layer::clearSyncPoints() {
2608     for (const auto& child : mCurrentChildren) {
2609         child->clearSyncPoints();
2610     }
2611
2612     Mutex::Autolock lock(mLocalSyncPointMutex);
2613     for (auto& point : mLocalSyncPoints) {
2614         point->setFrameAvailable();
2615     }
2616     mLocalSyncPoints.clear();
2617 }
2618
2619 int32_t Layer::getZ() const {
2620     return mDrawingState.z;
2621 }
2622
2623 LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2624     LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2625                         "makeTraversalList received invalid stateSet");
2626     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2627     const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2628     const State& state = useDrawing ? mDrawingState : mCurrentState;
2629
2630     if (state.zOrderRelatives.size() == 0) {
2631         return children;
2632     }
2633     LayerVector traverse;
2634
2635     for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2636         sp<Layer> strongRelative = weakRelative.promote();
2637         if (strongRelative != nullptr) {
2638             traverse.add(strongRelative);
2639         }
2640     }
2641
2642     for (const sp<Layer>& child : children) {
2643         traverse.add(child);
2644     }
2645
2646     return traverse;
2647 }
2648
2649 /**
2650  * Negatively signed relatives are before 'this' in Z-order.
2651  */
2652 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2653     LayerVector list = makeTraversalList(stateSet);
2654
2655     size_t i = 0;
2656     for (; i < list.size(); i++) {
2657         const auto& relative = list[i];
2658         if (relative->getZ() >= 0) {
2659             break;
2660         }
2661         relative->traverseInZOrder(stateSet, visitor);
2662     }
2663     visitor(this);
2664     for (; i < list.size(); i++) {
2665         const auto& relative = list[i];
2666         relative->traverseInZOrder(stateSet, visitor);
2667     }
2668 }
2669
2670 /**
2671  * Positively signed relatives are before 'this' in reverse Z-order.
2672  */
2673 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2674                                     const LayerVector::Visitor& visitor) {
2675     LayerVector list = makeTraversalList(stateSet);
2676
2677     int32_t i = 0;
2678     for (i = list.size()-1; i>=0; i--) {
2679         const auto& relative = list[i];
2680         if (relative->getZ() < 0) {
2681             break;
2682         }
2683         relative->traverseInReverseZOrder(stateSet, visitor);
2684     }
2685     visitor(this);
2686     for (; i>=0; i--) {
2687         const auto& relative = list[i];
2688         relative->traverseInReverseZOrder(stateSet, visitor);
2689     }
2690 }
2691
2692 Transform Layer::getTransform() const {
2693     Transform t;
2694     const auto& p = mDrawingParent.promote();
2695     if (p != nullptr) {
2696         t = p->getTransform();
2697
2698         // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2699         // it isFixedSize) then there may be additional scaling not accounted
2700         // for in the transform. We need to mirror this scaling in child surfaces
2701         // or we will break the contract where WM can treat child surfaces as
2702         // pixels in the parent surface.
2703         if (p->isFixedSize()) {
2704             int bufferWidth;
2705             int bufferHeight;
2706             if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2707                 bufferWidth = p->mActiveBuffer->getWidth();
2708                 bufferHeight = p->mActiveBuffer->getHeight();
2709             } else {
2710                 bufferHeight = p->mActiveBuffer->getWidth();
2711                 bufferWidth = p->mActiveBuffer->getHeight();
2712             }
2713             float sx = p->getDrawingState().active.w /
2714                     static_cast<float>(bufferWidth);
2715             float sy = p->getDrawingState().active.h /
2716                     static_cast<float>(bufferHeight);
2717             Transform extraParentScaling;
2718             extraParentScaling.set(sx, 0, 0, sy);
2719             t = t * extraParentScaling;
2720         }
2721     }
2722     return t * getDrawingState().active.transform;
2723 }
2724
2725 #ifdef USE_HWC2
2726 float Layer::getAlpha() const {
2727     const auto& p = mDrawingParent.promote();
2728
2729     float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2730     return parentAlpha * getDrawingState().alpha;
2731 }
2732 #else
2733 uint8_t Layer::getAlpha() const {
2734     const auto& p = mDrawingParent.promote();
2735
2736     float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2737     float drawingAlpha = getDrawingState().alpha / 255.0f;
2738     drawingAlpha = drawingAlpha * parentAlpha;
2739     return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2740 }
2741 #endif
2742
2743 void Layer::commitChildList() {
2744     for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2745         const auto& child = mCurrentChildren[i];
2746         child->commitChildList();
2747     }
2748     mDrawingChildren = mCurrentChildren;
2749     mDrawingParent = mCurrentParent;
2750 }
2751
2752 // ---------------------------------------------------------------------------
2753
2754 }; // namespace android
2755
2756 #if defined(__gl_h_)
2757 #error "don't include gl/gl.h in this file"
2758 #endif
2759
2760 #if defined(__gl2_h_)
2761 #error "don't include gl2/gl2.h in this file"
2762 #endif