OSDN Git Service

Merge "Add new MotionEvent flag for partially obscured windows." into mnc-dev am...
[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/GraphicBuffer.h>
38 #include <ui/PixelFormat.h>
39
40 #include <gui/BufferItem.h>
41 #include <gui/Surface.h>
42
43 #include "clz.h"
44 #include "Colorizer.h"
45 #include "DisplayDevice.h"
46 #include "Layer.h"
47 #include "MonitoredProducer.h"
48 #include "SurfaceFlinger.h"
49
50 #include "DisplayHardware/HWComposer.h"
51
52 #include "RenderEngine/RenderEngine.h"
53
54 #define DEBUG_RESIZE    0
55
56 namespace android {
57
58 // ---------------------------------------------------------------------------
59
60 int32_t Layer::sSequence = 1;
61
62 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
63         const String8& name, uint32_t w, uint32_t h, uint32_t flags)
64     :   contentDirty(false),
65         sequence(uint32_t(android_atomic_inc(&sSequence))),
66         mFlinger(flinger),
67         mTextureName(-1U),
68         mPremultipliedAlpha(true),
69         mName("unnamed"),
70         mFormat(PIXEL_FORMAT_NONE),
71         mTransactionFlags(0),
72         mPendingStateMutex(),
73         mPendingStates(),
74         mQueuedFrames(0),
75         mSidebandStreamChanged(false),
76         mCurrentTransform(0),
77         mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
78         mOverrideScalingMode(-1),
79         mCurrentOpacity(true),
80         mCurrentFrameNumber(0),
81         mRefreshPending(false),
82         mFrameLatencyNeeded(false),
83         mFiltering(false),
84         mNeedsFiltering(false),
85         mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
86 #ifndef USE_HWC2
87         mIsGlesComposition(false),
88 #endif
89         mProtectedByApp(false),
90         mHasSurface(false),
91         mClientRef(client),
92         mPotentialCursor(false),
93         mQueueItemLock(),
94         mQueueItemCondition(),
95         mQueueItems(),
96         mLastFrameNumberReceived(0),
97         mUpdateTexImageFailed(false),
98         mAutoRefresh(false)
99 {
100 #ifdef USE_HWC2
101     ALOGV("Creating Layer %s", name.string());
102 #endif
103
104     mCurrentCrop.makeInvalid();
105     mFlinger->getRenderEngine().genTextures(1, &mTextureName);
106     mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
107
108     uint32_t layerFlags = 0;
109     if (flags & ISurfaceComposerClient::eHidden)
110         layerFlags |= layer_state_t::eLayerHidden;
111     if (flags & ISurfaceComposerClient::eOpaque)
112         layerFlags |= layer_state_t::eLayerOpaque;
113     if (flags & ISurfaceComposerClient::eSecure)
114         layerFlags |= layer_state_t::eLayerSecure;
115
116     if (flags & ISurfaceComposerClient::eNonPremultiplied)
117         mPremultipliedAlpha = false;
118
119     mName = name;
120
121     mCurrentState.active.w = w;
122     mCurrentState.active.h = h;
123     mCurrentState.active.transform.set(0, 0);
124     mCurrentState.crop.makeInvalid();
125     mCurrentState.finalCrop.makeInvalid();
126     mCurrentState.z = 0;
127 #ifdef USE_HWC2
128     mCurrentState.alpha = 1.0f;
129 #else
130     mCurrentState.alpha = 0xFF;
131 #endif
132     mCurrentState.layerStack = 0;
133     mCurrentState.flags = layerFlags;
134     mCurrentState.sequence = 0;
135     mCurrentState.requested = mCurrentState.active;
136
137     // drawing state & current state are identical
138     mDrawingState = mCurrentState;
139
140 #ifdef USE_HWC2
141     const auto& hwc = flinger->getHwComposer();
142     const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
143     nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
144 #else
145     nsecs_t displayPeriod =
146             flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
147 #endif
148     mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
149 }
150
151 void Layer::onFirstRef() {
152     // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
153     sp<IGraphicBufferProducer> producer;
154     sp<IGraphicBufferConsumer> consumer;
155     BufferQueue::createBufferQueue(&producer, &consumer);
156     mProducer = new MonitoredProducer(producer, mFlinger);
157     mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
158     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
159     mSurfaceFlingerConsumer->setContentsChangedListener(this);
160     mSurfaceFlingerConsumer->setName(mName);
161
162 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
163 #warning "disabling triple buffering"
164 #else
165     mProducer->setMaxDequeuedBufferCount(2);
166 #endif
167
168     const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
169     updateTransformHint(hw);
170 }
171
172 Layer::~Layer() {
173   sp<Client> c(mClientRef.promote());
174     if (c != 0) {
175         c->detachLayer(this);
176     }
177
178     for (auto& point : mRemoteSyncPoints) {
179         point->setTransactionApplied();
180     }
181     mFlinger->deleteTextureAsync(mTextureName);
182     mFrameTracker.logAndResetStats(mName);
183 }
184
185 // ---------------------------------------------------------------------------
186 // callbacks
187 // ---------------------------------------------------------------------------
188
189 #ifdef USE_HWC2
190 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
191     if (mHwcLayers.empty()) {
192         return;
193     }
194     mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
195 }
196 #else
197 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
198         HWComposer::HWCLayerInterface* layer) {
199     if (layer) {
200         layer->onDisplayed();
201         mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
202     }
203 }
204 #endif
205
206 void Layer::onFrameAvailable(const BufferItem& item) {
207     // Add this buffer from our internal queue tracker
208     { // Autolock scope
209         Mutex::Autolock lock(mQueueItemLock);
210
211         // Reset the frame number tracker when we receive the first buffer after
212         // a frame number reset
213         if (item.mFrameNumber == 1) {
214             mLastFrameNumberReceived = 0;
215         }
216
217         // Ensure that callbacks are handled in order
218         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
219             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
220                     ms2ns(500));
221             if (result != NO_ERROR) {
222                 ALOGE("[%s] Timed out waiting on callback", mName.string());
223             }
224         }
225
226         mQueueItems.push_back(item);
227         android_atomic_inc(&mQueuedFrames);
228
229         // Wake up any pending callbacks
230         mLastFrameNumberReceived = item.mFrameNumber;
231         mQueueItemCondition.broadcast();
232     }
233
234     mFlinger->signalLayerUpdate();
235 }
236
237 void Layer::onFrameReplaced(const BufferItem& item) {
238     { // Autolock scope
239         Mutex::Autolock lock(mQueueItemLock);
240
241         // Ensure that callbacks are handled in order
242         while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
243             status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
244                     ms2ns(500));
245             if (result != NO_ERROR) {
246                 ALOGE("[%s] Timed out waiting on callback", mName.string());
247             }
248         }
249
250         if (mQueueItems.empty()) {
251             ALOGE("Can't replace a frame on an empty queue");
252             return;
253         }
254         mQueueItems.editItemAt(0) = item;
255
256         // Wake up any pending callbacks
257         mLastFrameNumberReceived = item.mFrameNumber;
258         mQueueItemCondition.broadcast();
259     }
260 }
261
262 void Layer::onSidebandStreamChanged() {
263     if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
264         // mSidebandStreamChanged was false
265         mFlinger->signalLayerUpdate();
266     }
267 }
268
269 // called with SurfaceFlinger::mStateLock from the drawing thread after
270 // the layer has been remove from the current state list (and just before
271 // it's removed from the drawing state list)
272 void Layer::onRemoved() {
273     mSurfaceFlingerConsumer->abandon();
274 }
275
276 // ---------------------------------------------------------------------------
277 // set-up
278 // ---------------------------------------------------------------------------
279
280 const String8& Layer::getName() const {
281     return mName;
282 }
283
284 status_t Layer::setBuffers( uint32_t w, uint32_t h,
285                             PixelFormat format, uint32_t flags)
286 {
287     uint32_t const maxSurfaceDims = min(
288             mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
289
290     // never allow a surface larger than what our underlying GL implementation
291     // can handle.
292     if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
293         ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
294         return BAD_VALUE;
295     }
296
297     mFormat = format;
298
299     mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
300     mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
301     mCurrentOpacity = getOpacityForFormat(format);
302
303     mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
304     mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
305     mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
306
307     return NO_ERROR;
308 }
309
310 /*
311  * The layer handle is just a BBinder object passed to the client
312  * (remote process) -- we don't keep any reference on our side such that
313  * the dtor is called when the remote side let go of its reference.
314  *
315  * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
316  * this layer when the handle is destroyed.
317  */
318 class Layer::Handle : public BBinder, public LayerCleaner {
319     public:
320         Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
321             : LayerCleaner(flinger, layer), owner(layer) {}
322
323         wp<Layer> owner;
324 };
325
326 sp<IBinder> Layer::getHandle() {
327     Mutex::Autolock _l(mLock);
328
329     LOG_ALWAYS_FATAL_IF(mHasSurface,
330             "Layer::getHandle() has already been called");
331
332     mHasSurface = true;
333
334     return new Handle(mFlinger, this);
335 }
336
337 sp<IGraphicBufferProducer> Layer::getProducer() const {
338     return mProducer;
339 }
340
341 // ---------------------------------------------------------------------------
342 // h/w composer set-up
343 // ---------------------------------------------------------------------------
344
345 Rect Layer::getContentCrop() const {
346     // this is the crop rectangle that applies to the buffer
347     // itself (as opposed to the window)
348     Rect crop;
349     if (!mCurrentCrop.isEmpty()) {
350         // if the buffer crop is defined, we use that
351         crop = mCurrentCrop;
352     } else if (mActiveBuffer != NULL) {
353         // otherwise we use the whole buffer
354         crop = mActiveBuffer->getBounds();
355     } else {
356         // if we don't have a buffer yet, we use an empty/invalid crop
357         crop.makeInvalid();
358     }
359     return crop;
360 }
361
362 static Rect reduce(const Rect& win, const Region& exclude) {
363     if (CC_LIKELY(exclude.isEmpty())) {
364         return win;
365     }
366     if (exclude.isRect()) {
367         return win.reduce(exclude.getBounds());
368     }
369     return Region(win).subtract(exclude).getBounds();
370 }
371
372 Rect Layer::computeBounds() const {
373     const Layer::State& s(getDrawingState());
374     return computeBounds(s.activeTransparentRegion);
375 }
376
377 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
378     const Layer::State& s(getDrawingState());
379     Rect win(s.active.w, s.active.h);
380
381     if (!s.crop.isEmpty()) {
382         win.intersect(s.crop, &win);
383     }
384     // subtract the transparent region and snap to the bounds
385     return reduce(win, activeTransparentRegion);
386 }
387
388 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
389     // the content crop is the area of the content that gets scaled to the
390     // layer's size.
391     FloatRect crop(getContentCrop());
392
393     // the crop is the area of the window that gets cropped, but not
394     // scaled in any ways.
395     const State& s(getDrawingState());
396
397     // apply the projection's clipping to the window crop in
398     // layerstack space, and convert-back to layer space.
399     // if there are no window scaling involved, this operation will map to full
400     // pixels in the buffer.
401     // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
402     // a viewport clipping and a window transform. we should use floating point to fix this.
403
404     Rect activeCrop(s.active.w, s.active.h);
405     if (!s.crop.isEmpty()) {
406         activeCrop = s.crop;
407     }
408
409     activeCrop = s.active.transform.transform(activeCrop);
410     if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
411         activeCrop.clear();
412     }
413     if (!s.finalCrop.isEmpty()) {
414         if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
415             activeCrop.clear();
416         }
417     }
418     activeCrop = s.active.transform.inverse().transform(activeCrop);
419
420     // This needs to be here as transform.transform(Rect) computes the
421     // transformed rect and then takes the bounding box of the result before
422     // returning. This means
423     // transform.inverse().transform(transform.transform(Rect)) != Rect
424     // in which case we need to make sure the final rect is clipped to the
425     // display bounds.
426     if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
427         activeCrop.clear();
428     }
429
430     // subtract the transparent region and snap to the bounds
431     activeCrop = reduce(activeCrop, s.activeTransparentRegion);
432
433     // Transform the window crop to match the buffer coordinate system,
434     // which means using the inverse of the current transform set on the
435     // SurfaceFlingerConsumer.
436     uint32_t invTransform = mCurrentTransform;
437     if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
438         /*
439          * the code below applies the display's inverse transform to the buffer
440          */
441         uint32_t invTransformOrient = hw->getOrientationTransform();
442         // calculate the inverse transform
443         if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
444             invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
445                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
446             // If the transform has been rotated the axis of flip has been swapped
447             // so we need to swap which flip operations we are performing
448             bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
449             bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
450             if (is_h_flipped != is_v_flipped) {
451                 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
452                         NATIVE_WINDOW_TRANSFORM_FLIP_H;
453             }
454         }
455         // and apply to the current transform
456         invTransform = (Transform(invTransform) * Transform(invTransformOrient)).getOrientation();
457     }
458
459     int winWidth = s.active.w;
460     int winHeight = s.active.h;
461     if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
462         // If the activeCrop has been rotate the ends are rotated but not
463         // the space itself so when transforming ends back we can't rely on
464         // a modification of the axes of rotation. To account for this we
465         // need to reorient the inverse rotation in terms of the current
466         // axes of rotation.
467         bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
468         bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
469         if (is_h_flipped == is_v_flipped) {
470             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
471                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
472         }
473         winWidth = s.active.h;
474         winHeight = s.active.w;
475     }
476     const Rect winCrop = activeCrop.transform(
477             invTransform, s.active.w, s.active.h);
478
479     // below, crop is intersected with winCrop expressed in crop's coordinate space
480     float xScale = crop.getWidth()  / float(winWidth);
481     float yScale = crop.getHeight() / float(winHeight);
482
483     float insetL = winCrop.left                 * xScale;
484     float insetT = winCrop.top                  * yScale;
485     float insetR = (winWidth - winCrop.right )  * xScale;
486     float insetB = (winHeight - winCrop.bottom) * yScale;
487
488     crop.left   += insetL;
489     crop.top    += insetT;
490     crop.right  -= insetR;
491     crop.bottom -= insetB;
492
493     return crop;
494 }
495
496 #ifdef USE_HWC2
497 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
498 #else
499 void Layer::setGeometry(
500     const sp<const DisplayDevice>& hw,
501         HWComposer::HWCLayerInterface& layer)
502 #endif
503 {
504 #ifdef USE_HWC2
505     const auto hwcId = displayDevice->getHwcDisplayId();
506     auto& hwcInfo = mHwcLayers[hwcId];
507 #else
508     layer.setDefaultState();
509 #endif
510
511     // enable this layer
512 #ifdef USE_HWC2
513     hwcInfo.forceClientComposition = false;
514
515     if (isSecure() && !displayDevice->isSecure()) {
516         hwcInfo.forceClientComposition = true;
517     }
518
519     auto& hwcLayer = hwcInfo.layer;
520 #else
521     layer.setSkip(false);
522
523     if (isSecure() && !hw->isSecure()) {
524         layer.setSkip(true);
525     }
526 #endif
527
528     // this gives us only the "orientation" component of the transform
529     const State& s(getDrawingState());
530 #ifdef USE_HWC2
531     if (!isOpaque(s) || s.alpha != 1.0f) {
532         auto blendMode = mPremultipliedAlpha ?
533                 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
534         auto error = hwcLayer->setBlendMode(blendMode);
535         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
536                 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
537                 to_string(error).c_str(), static_cast<int32_t>(error));
538     }
539 #else
540     if (!isOpaque(s) || s.alpha != 0xFF) {
541         layer.setBlending(mPremultipliedAlpha ?
542                 HWC_BLENDING_PREMULT :
543                 HWC_BLENDING_COVERAGE);
544     }
545 #endif
546
547     // apply the layer's transform, followed by the display's global transform
548     // here we're guaranteed that the layer's transform preserves rects
549     Region activeTransparentRegion(s.activeTransparentRegion);
550     if (!s.crop.isEmpty()) {
551         Rect activeCrop(s.crop);
552         activeCrop = s.active.transform.transform(activeCrop);
553 #ifdef USE_HWC2
554         if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
555 #else
556         if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
557 #endif
558             activeCrop.clear();
559         }
560         activeCrop = s.active.transform.inverse().transform(activeCrop);
561         // This needs to be here as transform.transform(Rect) computes the
562         // transformed rect and then takes the bounding box of the result before
563         // returning. This means
564         // transform.inverse().transform(transform.transform(Rect)) != Rect
565         // in which case we need to make sure the final rect is clipped to the
566         // display bounds.
567         if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
568             activeCrop.clear();
569         }
570         // mark regions outside the crop as transparent
571         activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
572         activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
573                 s.active.w, s.active.h));
574         activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
575                 activeCrop.left, activeCrop.bottom));
576         activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
577                 s.active.w, activeCrop.bottom));
578     }
579     Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
580     if (!s.finalCrop.isEmpty()) {
581         if(!frame.intersect(s.finalCrop, &frame)) {
582             frame.clear();
583         }
584     }
585 #ifdef USE_HWC2
586     if (!frame.intersect(displayDevice->getViewport(), &frame)) {
587         frame.clear();
588     }
589     const Transform& tr(displayDevice->getTransform());
590     Rect transformedFrame = tr.transform(frame);
591     auto error = hwcLayer->setDisplayFrame(transformedFrame);
592     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
593             "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
594             transformedFrame.top, transformedFrame.right,
595             transformedFrame.bottom, to_string(error).c_str(),
596             static_cast<int32_t>(error));
597
598     FloatRect sourceCrop = computeCrop(displayDevice);
599     error = hwcLayer->setSourceCrop(sourceCrop);
600     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
601             "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
602             sourceCrop.left, sourceCrop.top, sourceCrop.right,
603             sourceCrop.bottom, to_string(error).c_str(),
604             static_cast<int32_t>(error));
605
606     error = hwcLayer->setPlaneAlpha(s.alpha);
607     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
608             "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
609             static_cast<int32_t>(error));
610
611     error = hwcLayer->setZOrder(s.z);
612     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
613             mName.string(), s.z, to_string(error).c_str(),
614             static_cast<int32_t>(error));
615 #else
616     if (!frame.intersect(hw->getViewport(), &frame)) {
617         frame.clear();
618     }
619     const Transform& tr(hw->getTransform());
620     layer.setFrame(tr.transform(frame));
621     layer.setCrop(computeCrop(hw));
622     layer.setPlaneAlpha(s.alpha);
623 #endif
624
625     /*
626      * Transformations are applied in this order:
627      * 1) buffer orientation/flip/mirror
628      * 2) state transformation (window manager)
629      * 3) layer orientation (screen orientation)
630      * (NOTE: the matrices are multiplied in reverse order)
631      */
632
633     const Transform bufferOrientation(mCurrentTransform);
634     Transform transform(tr * s.active.transform * bufferOrientation);
635
636     if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
637         /*
638          * the code below applies the display's inverse transform to the buffer
639          */
640 #ifdef USE_HWC2
641         uint32_t invTransform = displayDevice->getOrientationTransform();
642 #else
643         uint32_t invTransform = hw->getOrientationTransform();
644 #endif
645         uint32_t t_orientation = transform.getOrientation();
646         // calculate the inverse transform
647         if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
648             invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
649                     NATIVE_WINDOW_TRANSFORM_FLIP_H;
650             // If the transform has been rotated the axis of flip has been swapped
651             // so we need to swap which flip operations we are performing
652             bool is_h_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
653             bool is_v_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
654             if (is_h_flipped != is_v_flipped) {
655                 t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
656                         NATIVE_WINDOW_TRANSFORM_FLIP_H;
657             }
658         }
659         // and apply to the current transform
660         transform = Transform(t_orientation) * Transform(invTransform);
661     }
662
663     // this gives us only the "orientation" component of the transform
664     const uint32_t orientation = transform.getOrientation();
665 #ifdef USE_HWC2
666     if (orientation & Transform::ROT_INVALID) {
667         // we can only handle simple transformation
668         hwcInfo.forceClientComposition = true;
669     } else {
670         auto transform = static_cast<HWC2::Transform>(orientation);
671         auto error = hwcLayer->setTransform(transform);
672         ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
673                 "%s (%d)", mName.string(), to_string(transform).c_str(),
674                 to_string(error).c_str(), static_cast<int32_t>(error));
675     }
676 #else
677     if (orientation & Transform::ROT_INVALID) {
678         // we can only handle simple transformation
679         layer.setSkip(true);
680     } else {
681         layer.setTransform(orientation);
682     }
683 #endif
684 }
685
686 #ifdef USE_HWC2
687 void Layer::forceClientComposition(int32_t hwcId) {
688     if (mHwcLayers.count(hwcId) == 0) {
689         ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
690         return;
691     }
692
693     mHwcLayers[hwcId].forceClientComposition = true;
694 }
695 #endif
696
697 #ifdef USE_HWC2
698 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
699     // Apply this display's projection's viewport to the visible region
700     // before giving it to the HWC HAL.
701     const Transform& tr = displayDevice->getTransform();
702     const auto& viewport = displayDevice->getViewport();
703     Region visible = tr.transform(visibleRegion.intersect(viewport));
704     auto hwcId = displayDevice->getHwcDisplayId();
705     auto& hwcLayer = mHwcLayers[hwcId].layer;
706     auto error = hwcLayer->setVisibleRegion(visible);
707     if (error != HWC2::Error::None) {
708         ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
709                 to_string(error).c_str(), static_cast<int32_t>(error));
710         visible.dump(LOG_TAG);
711     }
712
713     error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
714     if (error != HWC2::Error::None) {
715         ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
716                 to_string(error).c_str(), static_cast<int32_t>(error));
717         surfaceDamageRegion.dump(LOG_TAG);
718     }
719
720     auto compositionType = HWC2::Composition::Invalid;
721     if (mSidebandStream.get()) {
722         compositionType = HWC2::Composition::Sideband;
723         auto error = hwcLayer->setSidebandStream(mSidebandStream->handle());
724         if (error != HWC2::Error::None) {
725             ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
726                     mName.string(), mSidebandStream->handle(),
727                     to_string(error).c_str(), static_cast<int32_t>(error));
728             return;
729         }
730     } else {
731         if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr) {
732             compositionType = HWC2::Composition::Client;
733             auto error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
734             if (error != HWC2::Error::None) {
735                 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
736                         to_string(error).c_str(), static_cast<int32_t>(error));
737                 return;
738             }
739         } else {
740             if (mPotentialCursor) {
741                 compositionType = HWC2::Composition::Cursor;
742             }
743             auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
744             auto error = hwcLayer->setBuffer(mActiveBuffer->handle,
745                     acquireFence);
746             if (error != HWC2::Error::None) {
747                 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
748                         mActiveBuffer->handle, to_string(error).c_str(),
749                         static_cast<int32_t>(error));
750                 return;
751             }
752             // If it's not a cursor, default to device composition
753         }
754     }
755
756     if (mHwcLayers[hwcId].forceClientComposition) {
757         ALOGV("[%s] Forcing Client composition", mName.string());
758         setCompositionType(hwcId, HWC2::Composition::Client);
759     } else if (compositionType != HWC2::Composition::Invalid) {
760         ALOGV("[%s] Requesting %s composition", mName.string(),
761                 to_string(compositionType).c_str());
762         setCompositionType(hwcId, compositionType);
763     } else {
764         ALOGV("[%s] Requesting Device composition", mName.string());
765         setCompositionType(hwcId, HWC2::Composition::Device);
766     }
767 }
768 #else
769 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
770         HWComposer::HWCLayerInterface& layer) {
771     // we have to set the visible region on every frame because
772     // we currently free it during onLayerDisplayed(), which is called
773     // after HWComposer::commit() -- every frame.
774     // Apply this display's projection's viewport to the visible region
775     // before giving it to the HWC HAL.
776     const Transform& tr = hw->getTransform();
777     Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
778     layer.setVisibleRegionScreen(visible);
779     layer.setSurfaceDamage(surfaceDamageRegion);
780     mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
781
782     if (mSidebandStream.get()) {
783         layer.setSidebandStream(mSidebandStream);
784     } else {
785         // NOTE: buffer can be NULL if the client never drew into this
786         // layer yet, or if we ran out of memory
787         layer.setBuffer(mActiveBuffer);
788     }
789 }
790 #endif
791
792 #ifdef USE_HWC2
793 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
794     auto hwcId = displayDevice->getHwcDisplayId();
795     if (mHwcLayers.count(hwcId) == 0 ||
796             getCompositionType(hwcId) != HWC2::Composition::Cursor) {
797         return;
798     }
799
800     // This gives us only the "orientation" component of the transform
801     const State& s(getCurrentState());
802
803     // Apply the layer's transform, followed by the display's global transform
804     // Here we're guaranteed that the layer's transform preserves rects
805     Rect win(s.active.w, s.active.h);
806     if (!s.crop.isEmpty()) {
807         win.intersect(s.crop, &win);
808     }
809     // Subtract the transparent region and snap to the bounds
810     Rect bounds = reduce(win, s.activeTransparentRegion);
811     Rect frame(s.active.transform.transform(bounds));
812     frame.intersect(displayDevice->getViewport(), &frame);
813     if (!s.finalCrop.isEmpty()) {
814         frame.intersect(s.finalCrop, &frame);
815     }
816     auto& displayTransform(displayDevice->getTransform());
817     auto position = displayTransform.transform(frame);
818
819     auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
820             position.top);
821     ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
822             "to (%d, %d): %s (%d)", mName.string(), position.left,
823             position.top, to_string(error).c_str(),
824             static_cast<int32_t>(error));
825 }
826 #else
827 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
828         HWComposer::HWCLayerInterface& layer) {
829     int fenceFd = -1;
830
831     // TODO: there is a possible optimization here: we only need to set the
832     // acquire fence the first time a new buffer is acquired on EACH display.
833
834     if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
835         sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
836         if (fence->isValid()) {
837             fenceFd = fence->dup();
838             if (fenceFd == -1) {
839                 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
840             }
841         }
842     }
843     layer.setAcquireFenceFd(fenceFd);
844 }
845
846 Rect Layer::getPosition(
847     const sp<const DisplayDevice>& hw)
848 {
849     // this gives us only the "orientation" component of the transform
850     const State& s(getCurrentState());
851
852     // apply the layer's transform, followed by the display's global transform
853     // here we're guaranteed that the layer's transform preserves rects
854     Rect win(s.active.w, s.active.h);
855     if (!s.crop.isEmpty()) {
856         win.intersect(s.crop, &win);
857     }
858     // subtract the transparent region and snap to the bounds
859     Rect bounds = reduce(win, s.activeTransparentRegion);
860     Rect frame(s.active.transform.transform(bounds));
861     frame.intersect(hw->getViewport(), &frame);
862     if (!s.finalCrop.isEmpty()) {
863         frame.intersect(s.finalCrop, &frame);
864     }
865     const Transform& tr(hw->getTransform());
866     return Rect(tr.transform(frame));
867 }
868 #endif
869
870 // ---------------------------------------------------------------------------
871 // drawing...
872 // ---------------------------------------------------------------------------
873
874 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
875     onDraw(hw, clip, false);
876 }
877
878 void Layer::draw(const sp<const DisplayDevice>& hw,
879         bool useIdentityTransform) const {
880     onDraw(hw, Region(hw->bounds()), useIdentityTransform);
881 }
882
883 void Layer::draw(const sp<const DisplayDevice>& hw) const {
884     onDraw(hw, Region(hw->bounds()), false);
885 }
886
887 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
888         bool useIdentityTransform) const
889 {
890     ATRACE_CALL();
891
892     if (CC_UNLIKELY(mActiveBuffer == 0)) {
893         // the texture has not been created yet, this Layer has
894         // in fact never been drawn into. This happens frequently with
895         // SurfaceView because the WindowManager can't know when the client
896         // has drawn the first time.
897
898         // If there is nothing under us, we paint the screen in black, otherwise
899         // we just skip this update.
900
901         // figure out if there is something below us
902         Region under;
903         const SurfaceFlinger::LayerVector& drawingLayers(
904                 mFlinger->mDrawingState.layersSortedByZ);
905         const size_t count = drawingLayers.size();
906         for (size_t i=0 ; i<count ; ++i) {
907             const sp<Layer>& layer(drawingLayers[i]);
908             if (layer.get() == static_cast<Layer const*>(this))
909                 break;
910             under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
911         }
912         // if not everything below us is covered, we plug the holes!
913         Region holes(clip.subtract(under));
914         if (!holes.isEmpty()) {
915             clearWithOpenGL(hw, holes, 0, 0, 0, 1);
916         }
917         return;
918     }
919
920     // Bind the current buffer to the GL texture, and wait for it to be
921     // ready for us to draw into.
922     status_t err = mSurfaceFlingerConsumer->bindTextureImage();
923     if (err != NO_ERROR) {
924         ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
925         // Go ahead and draw the buffer anyway; no matter what we do the screen
926         // is probably going to have something visibly wrong.
927     }
928
929     bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
930
931     RenderEngine& engine(mFlinger->getRenderEngine());
932
933     if (!blackOutLayer) {
934         // TODO: we could be more subtle with isFixedSize()
935         const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
936
937         // Query the texture matrix given our current filtering mode.
938         float textureMatrix[16];
939         mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
940         mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
941
942         if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
943
944             /*
945              * the code below applies the display's inverse transform to the texture transform
946              */
947
948             // create a 4x4 transform matrix from the display transform flags
949             const mat4 flipH(-1,0,0,0,  0,1,0,0, 0,0,1,0, 1,0,0,1);
950             const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
951             const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
952
953             mat4 tr;
954             uint32_t transform = hw->getOrientationTransform();
955             if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
956                 tr = tr * rot90;
957             if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
958                 tr = tr * flipH;
959             if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
960                 tr = tr * flipV;
961
962             // calculate the inverse
963             tr = inverse(tr);
964
965             // and finally apply it to the original texture matrix
966             const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
967             memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
968         }
969
970         // Set things up for texturing.
971         mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
972         mTexture.setFiltering(useFiltering);
973         mTexture.setMatrix(textureMatrix);
974
975         engine.setupLayerTexturing(mTexture);
976     } else {
977         engine.setupLayerBlackedOut();
978     }
979     drawWithOpenGL(hw, clip, useIdentityTransform);
980     engine.disableTexturing();
981 }
982
983
984 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
985         const Region& /* clip */, float red, float green, float blue,
986         float alpha) const
987 {
988     RenderEngine& engine(mFlinger->getRenderEngine());
989     computeGeometry(hw, mMesh, false);
990     engine.setupFillWithColor(red, green, blue, alpha);
991     engine.drawMesh(mMesh);
992 }
993
994 void Layer::clearWithOpenGL(
995         const sp<const DisplayDevice>& hw, const Region& clip) const {
996     clearWithOpenGL(hw, clip, 0,0,0,0);
997 }
998
999 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1000         const Region& /* clip */, bool useIdentityTransform) const {
1001     const State& s(getDrawingState());
1002
1003     computeGeometry(hw, mMesh, useIdentityTransform);
1004
1005     /*
1006      * NOTE: the way we compute the texture coordinates here produces
1007      * different results than when we take the HWC path -- in the later case
1008      * the "source crop" is rounded to texel boundaries.
1009      * This can produce significantly different results when the texture
1010      * is scaled by a large amount.
1011      *
1012      * The GL code below is more logical (imho), and the difference with
1013      * HWC is due to a limitation of the HWC API to integers -- a question
1014      * is suspend is whether we should ignore this problem or revert to
1015      * GL composition when a buffer scaling is applied (maybe with some
1016      * minimal value)? Or, we could make GL behave like HWC -- but this feel
1017      * like more of a hack.
1018      */
1019     Rect win(computeBounds());
1020
1021     if (!s.finalCrop.isEmpty()) {
1022         win = s.active.transform.transform(win);
1023         if (!win.intersect(s.finalCrop, &win)) {
1024             win.clear();
1025         }
1026         win = s.active.transform.inverse().transform(win);
1027         if (!win.intersect(computeBounds(), &win)) {
1028             win.clear();
1029         }
1030     }
1031
1032     float left   = float(win.left)   / float(s.active.w);
1033     float top    = float(win.top)    / float(s.active.h);
1034     float right  = float(win.right)  / float(s.active.w);
1035     float bottom = float(win.bottom) / float(s.active.h);
1036
1037     // TODO: we probably want to generate the texture coords with the mesh
1038     // here we assume that we only have 4 vertices
1039     Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1040     texCoords[0] = vec2(left, 1.0f - top);
1041     texCoords[1] = vec2(left, 1.0f - bottom);
1042     texCoords[2] = vec2(right, 1.0f - bottom);
1043     texCoords[3] = vec2(right, 1.0f - top);
1044
1045     RenderEngine& engine(mFlinger->getRenderEngine());
1046     engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1047     engine.drawMesh(mMesh);
1048     engine.disableBlending();
1049 }
1050
1051 #ifdef USE_HWC2
1052 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1053         bool callIntoHwc) {
1054     if (mHwcLayers.count(hwcId) == 0) {
1055         ALOGE("setCompositionType called without a valid HWC layer");
1056         return;
1057     }
1058     auto& hwcInfo = mHwcLayers[hwcId];
1059     auto& hwcLayer = hwcInfo.layer;
1060     ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1061             to_string(type).c_str(), static_cast<int>(callIntoHwc));
1062     if (hwcInfo.compositionType != type) {
1063         ALOGV("    actually setting");
1064         hwcInfo.compositionType = type;
1065         if (callIntoHwc) {
1066             auto error = hwcLayer->setCompositionType(type);
1067             ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1068                     "composition type %s: %s (%d)", mName.string(),
1069                     to_string(type).c_str(), to_string(error).c_str(),
1070                     static_cast<int32_t>(error));
1071         }
1072     }
1073 }
1074
1075 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1076     if (mHwcLayers.count(hwcId) == 0) {
1077         ALOGE("getCompositionType called without a valid HWC layer");
1078         return HWC2::Composition::Invalid;
1079     }
1080     return mHwcLayers.at(hwcId).compositionType;
1081 }
1082
1083 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1084     if (mHwcLayers.count(hwcId) == 0) {
1085         ALOGE("setClearClientTarget called without a valid HWC layer");
1086         return;
1087     }
1088     mHwcLayers[hwcId].clearClientTarget = clear;
1089 }
1090
1091 bool Layer::getClearClientTarget(int32_t hwcId) const {
1092     if (mHwcLayers.count(hwcId) == 0) {
1093         ALOGE("getClearClientTarget called without a valid HWC layer");
1094         return false;
1095     }
1096     return mHwcLayers.at(hwcId).clearClientTarget;
1097 }
1098 #endif
1099
1100 uint32_t Layer::getProducerStickyTransform() const {
1101     int producerStickyTransform = 0;
1102     int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1103     if (ret != OK) {
1104         ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1105                 strerror(-ret), ret);
1106         return 0;
1107     }
1108     return static_cast<uint32_t>(producerStickyTransform);
1109 }
1110
1111 uint64_t Layer::getHeadFrameNumber() const {
1112     Mutex::Autolock lock(mQueueItemLock);
1113     if (!mQueueItems.empty()) {
1114         return mQueueItems[0].mFrameNumber;
1115     } else {
1116         return mCurrentFrameNumber;
1117     }
1118 }
1119
1120 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1121     if (point->getFrameNumber() <= mCurrentFrameNumber) {
1122         // Don't bother with a SyncPoint, since we've already latched the
1123         // relevant frame
1124         return false;
1125     }
1126
1127     Mutex::Autolock lock(mLocalSyncPointMutex);
1128     mLocalSyncPoints.push_back(point);
1129     return true;
1130 }
1131
1132 void Layer::setFiltering(bool filtering) {
1133     mFiltering = filtering;
1134 }
1135
1136 bool Layer::getFiltering() const {
1137     return mFiltering;
1138 }
1139
1140 // As documented in libhardware header, formats in the range
1141 // 0x100 - 0x1FF are specific to the HAL implementation, and
1142 // are known to have no alpha channel
1143 // TODO: move definition for device-specific range into
1144 // hardware.h, instead of using hard-coded values here.
1145 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1146
1147 bool Layer::getOpacityForFormat(uint32_t format) {
1148     if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1149         return true;
1150     }
1151     switch (format) {
1152         case HAL_PIXEL_FORMAT_RGBA_8888:
1153         case HAL_PIXEL_FORMAT_BGRA_8888:
1154             return false;
1155     }
1156     // in all other case, we have no blending (also for unknown formats)
1157     return true;
1158 }
1159
1160 // ----------------------------------------------------------------------------
1161 // local state
1162 // ----------------------------------------------------------------------------
1163
1164 static void boundPoint(vec2* point, const Rect& crop) {
1165     if (point->x < crop.left) {
1166         point->x = crop.left;
1167     }
1168     if (point->x > crop.right) {
1169         point->x = crop.right;
1170     }
1171     if (point->y < crop.top) {
1172         point->y = crop.top;
1173     }
1174     if (point->y > crop.bottom) {
1175         point->y = crop.bottom;
1176     }
1177 }
1178
1179 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1180         bool useIdentityTransform) const
1181 {
1182     const Layer::State& s(getDrawingState());
1183     const Transform tr(hw->getTransform());
1184     const uint32_t hw_h = hw->getHeight();
1185     Rect win(s.active.w, s.active.h);
1186     if (!s.crop.isEmpty()) {
1187         win.intersect(s.crop, &win);
1188     }
1189     // subtract the transparent region and snap to the bounds
1190     win = reduce(win, s.activeTransparentRegion);
1191
1192     vec2 lt = vec2(win.left, win.top);
1193     vec2 lb = vec2(win.left, win.bottom);
1194     vec2 rb = vec2(win.right, win.bottom);
1195     vec2 rt = vec2(win.right, win.top);
1196
1197     if (!useIdentityTransform) {
1198         lt = s.active.transform.transform(lt);
1199         lb = s.active.transform.transform(lb);
1200         rb = s.active.transform.transform(rb);
1201         rt = s.active.transform.transform(rt);
1202     }
1203
1204     if (!s.finalCrop.isEmpty()) {
1205         boundPoint(&lt, s.finalCrop);
1206         boundPoint(&lb, s.finalCrop);
1207         boundPoint(&rb, s.finalCrop);
1208         boundPoint(&rt, s.finalCrop);
1209     }
1210
1211     Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1212     position[0] = tr.transform(lt);
1213     position[1] = tr.transform(lb);
1214     position[2] = tr.transform(rb);
1215     position[3] = tr.transform(rt);
1216     for (size_t i=0 ; i<4 ; i++) {
1217         position[i].y = hw_h - position[i].y;
1218     }
1219 }
1220
1221 bool Layer::isOpaque(const Layer::State& s) const
1222 {
1223     // if we don't have a buffer yet, we're translucent regardless of the
1224     // layer's opaque flag.
1225     if (mActiveBuffer == 0) {
1226         return false;
1227     }
1228
1229     // if the layer has the opaque flag, then we're always opaque,
1230     // otherwise we use the current buffer's format.
1231     return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1232 }
1233
1234 bool Layer::isSecure() const
1235 {
1236     const Layer::State& s(mDrawingState);
1237     return (s.flags & layer_state_t::eLayerSecure);
1238 }
1239
1240 bool Layer::isProtected() const
1241 {
1242     const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1243     return (activeBuffer != 0) &&
1244             (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1245 }
1246
1247 bool Layer::isFixedSize() const {
1248     return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1249 }
1250
1251 bool Layer::isCropped() const {
1252     return !mCurrentCrop.isEmpty();
1253 }
1254
1255 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1256     return mNeedsFiltering || hw->needsFiltering();
1257 }
1258
1259 void Layer::setVisibleRegion(const Region& visibleRegion) {
1260     // always called from main thread
1261     this->visibleRegion = visibleRegion;
1262 }
1263
1264 void Layer::setCoveredRegion(const Region& coveredRegion) {
1265     // always called from main thread
1266     this->coveredRegion = coveredRegion;
1267 }
1268
1269 void Layer::setVisibleNonTransparentRegion(const Region&
1270         setVisibleNonTransparentRegion) {
1271     // always called from main thread
1272     this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1273 }
1274
1275 // ----------------------------------------------------------------------------
1276 // transaction
1277 // ----------------------------------------------------------------------------
1278
1279 void Layer::pushPendingState() {
1280     if (!mCurrentState.modified) {
1281         return;
1282     }
1283
1284     // If this transaction is waiting on the receipt of a frame, generate a sync
1285     // point and send it to the remote layer.
1286     if (mCurrentState.handle != nullptr) {
1287         sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1288         sp<Layer> handleLayer = handle->owner.promote();
1289         if (handleLayer == nullptr) {
1290             ALOGE("[%s] Unable to promote Layer handle", mName.string());
1291             // If we can't promote the layer we are intended to wait on,
1292             // then it is expired or otherwise invalid. Allow this transaction
1293             // to be applied as per normal (no synchronization).
1294             mCurrentState.handle = nullptr;
1295         } else {
1296             auto syncPoint = std::make_shared<SyncPoint>(
1297                     mCurrentState.frameNumber);
1298             if (handleLayer->addSyncPoint(syncPoint)) {
1299                 mRemoteSyncPoints.push_back(std::move(syncPoint));
1300             } else {
1301                 // We already missed the frame we're supposed to synchronize
1302                 // on, so go ahead and apply the state update
1303                 mCurrentState.handle = nullptr;
1304             }
1305         }
1306
1307         // Wake us up to check if the frame has been received
1308         setTransactionFlags(eTransactionNeeded);
1309     }
1310     mPendingStates.push_back(mCurrentState);
1311 }
1312
1313 void Layer::popPendingState(State* stateToCommit) {
1314     auto oldFlags = stateToCommit->flags;
1315     *stateToCommit = mPendingStates[0];
1316     stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1317             (stateToCommit->flags & stateToCommit->mask);
1318
1319     mPendingStates.removeAt(0);
1320 }
1321
1322 bool Layer::applyPendingStates(State* stateToCommit) {
1323     bool stateUpdateAvailable = false;
1324     while (!mPendingStates.empty()) {
1325         if (mPendingStates[0].handle != nullptr) {
1326             if (mRemoteSyncPoints.empty()) {
1327                 // If we don't have a sync point for this, apply it anyway. It
1328                 // will be visually wrong, but it should keep us from getting
1329                 // into too much trouble.
1330                 ALOGE("[%s] No local sync point found", mName.string());
1331                 popPendingState(stateToCommit);
1332                 stateUpdateAvailable = true;
1333                 continue;
1334             }
1335
1336             if (mRemoteSyncPoints.front()->getFrameNumber() !=
1337                     mPendingStates[0].frameNumber) {
1338                 ALOGE("[%s] Unexpected sync point frame number found",
1339                         mName.string());
1340
1341                 // Signal our end of the sync point and then dispose of it
1342                 mRemoteSyncPoints.front()->setTransactionApplied();
1343                 mRemoteSyncPoints.pop_front();
1344                 continue;
1345             }
1346
1347             if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1348                 // Apply the state update
1349                 popPendingState(stateToCommit);
1350                 stateUpdateAvailable = true;
1351
1352                 // Signal our end of the sync point and then dispose of it
1353                 mRemoteSyncPoints.front()->setTransactionApplied();
1354                 mRemoteSyncPoints.pop_front();
1355             } else {
1356                 break;
1357             }
1358         } else {
1359             popPendingState(stateToCommit);
1360             stateUpdateAvailable = true;
1361         }
1362     }
1363
1364     // If we still have pending updates, wake SurfaceFlinger back up and point
1365     // it at this layer so we can process them
1366     if (!mPendingStates.empty()) {
1367         setTransactionFlags(eTransactionNeeded);
1368         mFlinger->setTransactionFlags(eTraversalNeeded);
1369     }
1370
1371     mCurrentState.modified = false;
1372     return stateUpdateAvailable;
1373 }
1374
1375 void Layer::notifyAvailableFrames() {
1376     auto headFrameNumber = getHeadFrameNumber();
1377     Mutex::Autolock lock(mLocalSyncPointMutex);
1378     for (auto& point : mLocalSyncPoints) {
1379         if (headFrameNumber >= point->getFrameNumber()) {
1380             point->setFrameAvailable();
1381         }
1382     }
1383 }
1384
1385 uint32_t Layer::doTransaction(uint32_t flags) {
1386     ATRACE_CALL();
1387
1388     pushPendingState();
1389     Layer::State c = getCurrentState();
1390     if (!applyPendingStates(&c)) {
1391         return 0;
1392     }
1393
1394     const Layer::State& s(getDrawingState());
1395
1396     const bool sizeChanged = (c.requested.w != s.requested.w) ||
1397                              (c.requested.h != s.requested.h);
1398
1399     if (sizeChanged) {
1400         // the size changed, we need to ask our client to request a new buffer
1401         ALOGD_IF(DEBUG_RESIZE,
1402                 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1403                 "  current={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1404                 "            requested={ wh={%4u,%4u} }}\n"
1405                 "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1406                 "            requested={ wh={%4u,%4u} }}\n",
1407                 this, getName().string(), mCurrentTransform,
1408                 getEffectiveScalingMode(),
1409                 c.active.w, c.active.h,
1410                 c.crop.left,
1411                 c.crop.top,
1412                 c.crop.right,
1413                 c.crop.bottom,
1414                 c.crop.getWidth(),
1415                 c.crop.getHeight(),
1416                 c.requested.w, c.requested.h,
1417                 s.active.w, s.active.h,
1418                 s.crop.left,
1419                 s.crop.top,
1420                 s.crop.right,
1421                 s.crop.bottom,
1422                 s.crop.getWidth(),
1423                 s.crop.getHeight(),
1424                 s.requested.w, s.requested.h);
1425
1426         // record the new size, form this point on, when the client request
1427         // a buffer, it'll get the new size.
1428         mSurfaceFlingerConsumer->setDefaultBufferSize(
1429                 c.requested.w, c.requested.h);
1430     }
1431
1432     if (!isFixedSize()) {
1433
1434         const bool resizePending = (c.requested.w != c.active.w) ||
1435                                    (c.requested.h != c.active.h);
1436
1437         if (resizePending && mSidebandStream == NULL) {
1438             // don't let Layer::doTransaction update the drawing state
1439             // if we have a pending resize, unless we are in fixed-size mode.
1440             // the drawing state will be updated only once we receive a buffer
1441             // with the correct size.
1442             //
1443             // in particular, we want to make sure the clip (which is part
1444             // of the geometry state) is latched together with the size but is
1445             // latched immediately when no resizing is involved.
1446             //
1447             // If a sideband stream is attached, however, we want to skip this
1448             // optimization so that transactions aren't missed when a buffer
1449             // never arrives
1450
1451             flags |= eDontUpdateGeometryState;
1452         }
1453     }
1454
1455     // always set active to requested, unless we're asked not to
1456     // this is used by Layer, which special cases resizes.
1457     if (flags & eDontUpdateGeometryState)  {
1458     } else {
1459         c.active = c.requested;
1460     }
1461
1462     if (s.active != c.active) {
1463         // invalidate and recompute the visible regions if needed
1464         flags |= Layer::eVisibleRegion;
1465     }
1466
1467     if (c.sequence != s.sequence) {
1468         // invalidate and recompute the visible regions if needed
1469         flags |= eVisibleRegion;
1470         this->contentDirty = true;
1471
1472         // we may use linear filtering, if the matrix scales us
1473         const uint8_t type = c.active.transform.getType();
1474         mNeedsFiltering = (!c.active.transform.preserveRects() ||
1475                 (type >= Transform::SCALE));
1476     }
1477
1478     // Commit the transaction
1479     commitTransaction(c);
1480     return flags;
1481 }
1482
1483 void Layer::commitTransaction(const State& stateToCommit) {
1484     mDrawingState = stateToCommit;
1485 }
1486
1487 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1488     return android_atomic_and(~flags, &mTransactionFlags) & flags;
1489 }
1490
1491 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1492     return android_atomic_or(flags, &mTransactionFlags);
1493 }
1494
1495 bool Layer::setPosition(float x, float y) {
1496     if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1497         return false;
1498     mCurrentState.sequence++;
1499
1500     // We update the requested and active position simultaneously because
1501     // we want to apply the position portion of the transform matrix immediately,
1502     // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1503     mCurrentState.requested.transform.set(x, y);
1504     mCurrentState.active.transform.set(x, y);
1505
1506     mCurrentState.modified = true;
1507     setTransactionFlags(eTransactionNeeded);
1508     return true;
1509 }
1510 bool Layer::setLayer(uint32_t z) {
1511     if (mCurrentState.z == z)
1512         return false;
1513     mCurrentState.sequence++;
1514     mCurrentState.z = z;
1515     mCurrentState.modified = true;
1516     setTransactionFlags(eTransactionNeeded);
1517     return true;
1518 }
1519 bool Layer::setSize(uint32_t w, uint32_t h) {
1520     if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1521         return false;
1522     mCurrentState.requested.w = w;
1523     mCurrentState.requested.h = h;
1524     mCurrentState.modified = true;
1525     setTransactionFlags(eTransactionNeeded);
1526     return true;
1527 }
1528 #ifdef USE_HWC2
1529 bool Layer::setAlpha(float alpha) {
1530 #else
1531 bool Layer::setAlpha(uint8_t alpha) {
1532 #endif
1533     if (mCurrentState.alpha == alpha)
1534         return false;
1535     mCurrentState.sequence++;
1536     mCurrentState.alpha = alpha;
1537     mCurrentState.modified = true;
1538     setTransactionFlags(eTransactionNeeded);
1539     return true;
1540 }
1541 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1542     mCurrentState.sequence++;
1543     mCurrentState.requested.transform.set(
1544             matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1545     mCurrentState.modified = true;
1546     setTransactionFlags(eTransactionNeeded);
1547     return true;
1548 }
1549 bool Layer::setTransparentRegionHint(const Region& transparent) {
1550     mCurrentState.requestedTransparentRegion = transparent;
1551     mCurrentState.modified = true;
1552     setTransactionFlags(eTransactionNeeded);
1553     return true;
1554 }
1555 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1556     const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1557     if (mCurrentState.flags == newFlags)
1558         return false;
1559     mCurrentState.sequence++;
1560     mCurrentState.flags = newFlags;
1561     mCurrentState.mask = mask;
1562     mCurrentState.modified = true;
1563     setTransactionFlags(eTransactionNeeded);
1564     return true;
1565 }
1566 bool Layer::setCrop(const Rect& crop) {
1567     if (mCurrentState.crop == crop)
1568         return false;
1569     mCurrentState.sequence++;
1570     mCurrentState.crop = crop;
1571     mCurrentState.modified = true;
1572     setTransactionFlags(eTransactionNeeded);
1573     return true;
1574 }
1575 bool Layer::setFinalCrop(const Rect& crop) {
1576     if (mCurrentState.finalCrop == crop)
1577         return false;
1578     mCurrentState.sequence++;
1579     mCurrentState.finalCrop = crop;
1580     mCurrentState.modified = true;
1581     setTransactionFlags(eTransactionNeeded);
1582     return true;
1583 }
1584
1585 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1586     if (scalingMode == mOverrideScalingMode)
1587         return false;
1588     mOverrideScalingMode = scalingMode;
1589     return true;
1590 }
1591
1592 uint32_t Layer::getEffectiveScalingMode() const {
1593     if (mOverrideScalingMode >= 0) {
1594       return mOverrideScalingMode;
1595     }
1596     return mCurrentScalingMode;
1597 }
1598
1599 bool Layer::setLayerStack(uint32_t layerStack) {
1600     if (mCurrentState.layerStack == layerStack)
1601         return false;
1602     mCurrentState.sequence++;
1603     mCurrentState.layerStack = layerStack;
1604     mCurrentState.modified = true;
1605     setTransactionFlags(eTransactionNeeded);
1606     return true;
1607 }
1608
1609 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1610         uint64_t frameNumber) {
1611     mCurrentState.handle = handle;
1612     mCurrentState.frameNumber = frameNumber;
1613     // We don't set eTransactionNeeded, because just receiving a deferral
1614     // request without any other state updates shouldn't actually induce a delay
1615     mCurrentState.modified = true;
1616     pushPendingState();
1617     mCurrentState.handle = nullptr;
1618     mCurrentState.frameNumber = 0;
1619     mCurrentState.modified = false;
1620 }
1621
1622 void Layer::useSurfaceDamage() {
1623     if (mFlinger->mForceFullDamage) {
1624         surfaceDamageRegion = Region::INVALID_REGION;
1625     } else {
1626         surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1627     }
1628 }
1629
1630 void Layer::useEmptyDamage() {
1631     surfaceDamageRegion.clear();
1632 }
1633
1634 // ----------------------------------------------------------------------------
1635 // pageflip handling...
1636 // ----------------------------------------------------------------------------
1637
1638 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1639     if (mSidebandStreamChanged || mAutoRefresh) {
1640         return true;
1641     }
1642
1643     Mutex::Autolock lock(mQueueItemLock);
1644     if (mQueueItems.empty()) {
1645         return false;
1646     }
1647     auto timestamp = mQueueItems[0].mTimestamp;
1648     nsecs_t expectedPresent =
1649             mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1650
1651     // Ignore timestamps more than a second in the future
1652     bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1653     ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1654             "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1655             expectedPresent);
1656
1657     bool isDue = timestamp < expectedPresent;
1658     return isDue || !isPlausible;
1659 }
1660
1661 bool Layer::onPreComposition() {
1662     mRefreshPending = false;
1663     return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1664 }
1665
1666 void Layer::onPostComposition() {
1667     if (mFrameLatencyNeeded) {
1668         nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1669         mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1670
1671         sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1672         if (frameReadyFence->isValid()) {
1673             mFrameTracker.setFrameReadyFence(frameReadyFence);
1674         } else {
1675             // There was no fence for this frame, so assume that it was ready
1676             // to be presented at the desired present time.
1677             mFrameTracker.setFrameReadyTime(desiredPresentTime);
1678         }
1679
1680         const HWComposer& hwc = mFlinger->getHwComposer();
1681 #ifdef USE_HWC2
1682         sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1683 #else
1684         sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1685 #endif
1686         if (presentFence->isValid()) {
1687             mFrameTracker.setActualPresentFence(presentFence);
1688         } else {
1689             // The HWC doesn't support present fences, so use the refresh
1690             // timestamp instead.
1691             nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1692             mFrameTracker.setActualPresentTime(presentTime);
1693         }
1694
1695         mFrameTracker.advanceFrame();
1696         mFrameLatencyNeeded = false;
1697     }
1698 }
1699
1700 #ifdef USE_HWC2
1701 void Layer::releasePendingBuffer() {
1702     mSurfaceFlingerConsumer->releasePendingBuffer();
1703 }
1704 #endif
1705
1706 bool Layer::isVisible() const {
1707     const Layer::State& s(mDrawingState);
1708 #ifdef USE_HWC2
1709     return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1710             && (mActiveBuffer != NULL || mSidebandStream != NULL);
1711 #else
1712     return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1713             && (mActiveBuffer != NULL || mSidebandStream != NULL);
1714 #endif
1715 }
1716
1717 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1718 {
1719     ATRACE_CALL();
1720
1721     if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1722         // mSidebandStreamChanged was true
1723         mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1724         if (mSidebandStream != NULL) {
1725             setTransactionFlags(eTransactionNeeded);
1726             mFlinger->setTransactionFlags(eTraversalNeeded);
1727         }
1728         recomputeVisibleRegions = true;
1729
1730         const State& s(getDrawingState());
1731         return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1732     }
1733
1734     Region outDirtyRegion;
1735     if (mQueuedFrames > 0 || mAutoRefresh) {
1736
1737         // if we've already called updateTexImage() without going through
1738         // a composition step, we have to skip this layer at this point
1739         // because we cannot call updateTeximage() without a corresponding
1740         // compositionComplete() call.
1741         // we'll trigger an update in onPreComposition().
1742         if (mRefreshPending) {
1743             return outDirtyRegion;
1744         }
1745
1746         // Capture the old state of the layer for comparisons later
1747         const State& s(getDrawingState());
1748         const bool oldOpacity = isOpaque(s);
1749         sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1750
1751         struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1752             Layer::State& front;
1753             Layer::State& current;
1754             bool& recomputeVisibleRegions;
1755             bool stickyTransformSet;
1756             const char* name;
1757             int32_t overrideScalingMode;
1758
1759             Reject(Layer::State& front, Layer::State& current,
1760                     bool& recomputeVisibleRegions, bool stickySet,
1761                     const char* name,
1762                     int32_t overrideScalingMode)
1763                 : front(front), current(current),
1764                   recomputeVisibleRegions(recomputeVisibleRegions),
1765                   stickyTransformSet(stickySet),
1766                   name(name),
1767                   overrideScalingMode(overrideScalingMode) {
1768             }
1769
1770             virtual bool reject(const sp<GraphicBuffer>& buf,
1771                     const BufferItem& item) {
1772                 if (buf == NULL) {
1773                     return false;
1774                 }
1775
1776                 uint32_t bufWidth  = buf->getWidth();
1777                 uint32_t bufHeight = buf->getHeight();
1778
1779                 // check that we received a buffer of the right size
1780                 // (Take the buffer's orientation into account)
1781                 if (item.mTransform & Transform::ROT_90) {
1782                     swap(bufWidth, bufHeight);
1783                 }
1784
1785                 int actualScalingMode = overrideScalingMode >= 0 ?
1786                         overrideScalingMode : item.mScalingMode;
1787                 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1788                 if (front.active != front.requested) {
1789
1790                     if (isFixedSize ||
1791                             (bufWidth == front.requested.w &&
1792                              bufHeight == front.requested.h))
1793                     {
1794                         // Here we pretend the transaction happened by updating the
1795                         // current and drawing states. Drawing state is only accessed
1796                         // in this thread, no need to have it locked
1797                         front.active = front.requested;
1798
1799                         // We also need to update the current state so that
1800                         // we don't end-up overwriting the drawing state with
1801                         // this stale current state during the next transaction
1802                         //
1803                         // NOTE: We don't need to hold the transaction lock here
1804                         // because State::active is only accessed from this thread.
1805                         current.active = front.active;
1806
1807                         // recompute visible region
1808                         recomputeVisibleRegions = true;
1809                     }
1810
1811                     ALOGD_IF(DEBUG_RESIZE,
1812                             "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1813                             "  drawing={ active   ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1814                             "            requested={ wh={%4u,%4u} }}\n",
1815                             name,
1816                             bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1817                             front.active.w, front.active.h,
1818                             front.crop.left,
1819                             front.crop.top,
1820                             front.crop.right,
1821                             front.crop.bottom,
1822                             front.crop.getWidth(),
1823                             front.crop.getHeight(),
1824                             front.requested.w, front.requested.h);
1825                 }
1826
1827                 if (!isFixedSize && !stickyTransformSet) {
1828                     if (front.active.w != bufWidth ||
1829                         front.active.h != bufHeight) {
1830                         // reject this buffer
1831                         ALOGE("[%s] rejecting buffer: "
1832                                 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1833                                 name, bufWidth, bufHeight, front.active.w, front.active.h);
1834                         return true;
1835                     }
1836                 }
1837
1838                 // if the transparent region has changed (this test is
1839                 // conservative, but that's fine, worst case we're doing
1840                 // a bit of extra work), we latch the new one and we
1841                 // trigger a visible-region recompute.
1842                 if (!front.activeTransparentRegion.isTriviallyEqual(
1843                         front.requestedTransparentRegion)) {
1844                     front.activeTransparentRegion = front.requestedTransparentRegion;
1845
1846                     // We also need to update the current state so that
1847                     // we don't end-up overwriting the drawing state with
1848                     // this stale current state during the next transaction
1849                     //
1850                     // NOTE: We don't need to hold the transaction lock here
1851                     // because State::active is only accessed from this thread.
1852                     current.activeTransparentRegion = front.activeTransparentRegion;
1853
1854                     // recompute visible region
1855                     recomputeVisibleRegions = true;
1856                 }
1857
1858                 return false;
1859             }
1860         };
1861
1862         Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1863                 getProducerStickyTransform() != 0, mName.string(),
1864                 mOverrideScalingMode);
1865
1866
1867         // Check all of our local sync points to ensure that all transactions
1868         // which need to have been applied prior to the frame which is about to
1869         // be latched have signaled
1870
1871         auto headFrameNumber = getHeadFrameNumber();
1872         bool matchingFramesFound = false;
1873         bool allTransactionsApplied = true;
1874         {
1875             Mutex::Autolock lock(mLocalSyncPointMutex);
1876             for (auto& point : mLocalSyncPoints) {
1877                 if (point->getFrameNumber() > headFrameNumber) {
1878                     break;
1879                 }
1880
1881                 matchingFramesFound = true;
1882
1883                 if (!point->frameIsAvailable()) {
1884                     // We haven't notified the remote layer that the frame for
1885                     // this point is available yet. Notify it now, and then
1886                     // abort this attempt to latch.
1887                     point->setFrameAvailable();
1888                     allTransactionsApplied = false;
1889                     break;
1890                 }
1891
1892                 allTransactionsApplied &= point->transactionIsApplied();
1893             }
1894         }
1895
1896         if (matchingFramesFound && !allTransactionsApplied) {
1897             mFlinger->signalLayerUpdate();
1898             return outDirtyRegion;
1899         }
1900
1901         // This boolean is used to make sure that SurfaceFlinger's shadow copy
1902         // of the buffer queue isn't modified when the buffer queue is returning
1903         // BufferItem's that weren't actually queued. This can happen in shared
1904         // buffer mode.
1905         bool queuedBuffer = false;
1906         status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1907                 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1908                 mLastFrameNumberReceived);
1909         if (updateResult == BufferQueue::PRESENT_LATER) {
1910             // Producer doesn't want buffer to be displayed yet.  Signal a
1911             // layer update so we check again at the next opportunity.
1912             mFlinger->signalLayerUpdate();
1913             return outDirtyRegion;
1914         } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1915             // If the buffer has been rejected, remove it from the shadow queue
1916             // and return early
1917             if (queuedBuffer) {
1918                 Mutex::Autolock lock(mQueueItemLock);
1919                 mQueueItems.removeAt(0);
1920                 android_atomic_dec(&mQueuedFrames);
1921             }
1922             return outDirtyRegion;
1923         } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1924             // This can occur if something goes wrong when trying to create the
1925             // EGLImage for this buffer. If this happens, the buffer has already
1926             // been released, so we need to clean up the queue and bug out
1927             // early.
1928             if (queuedBuffer) {
1929                 Mutex::Autolock lock(mQueueItemLock);
1930                 mQueueItems.clear();
1931                 android_atomic_and(0, &mQueuedFrames);
1932             }
1933
1934             // Once we have hit this state, the shadow queue may no longer
1935             // correctly reflect the incoming BufferQueue's contents, so even if
1936             // updateTexImage starts working, the only safe course of action is
1937             // to continue to ignore updates.
1938             mUpdateTexImageFailed = true;
1939
1940             return outDirtyRegion;
1941         }
1942
1943         if (queuedBuffer) {
1944             // Autolock scope
1945             auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1946
1947             Mutex::Autolock lock(mQueueItemLock);
1948
1949             // Remove any stale buffers that have been dropped during
1950             // updateTexImage
1951             while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1952                 mQueueItems.removeAt(0);
1953                 android_atomic_dec(&mQueuedFrames);
1954             }
1955
1956             mQueueItems.removeAt(0);
1957         }
1958
1959
1960         // Decrement the queued-frames count.  Signal another event if we
1961         // have more frames pending.
1962         if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1963                 || mAutoRefresh) {
1964             mFlinger->signalLayerUpdate();
1965         }
1966
1967         if (updateResult != NO_ERROR) {
1968             // something happened!
1969             recomputeVisibleRegions = true;
1970             return outDirtyRegion;
1971         }
1972
1973         // update the active buffer
1974         mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1975         if (mActiveBuffer == NULL) {
1976             // this can only happen if the very first buffer was rejected.
1977             return outDirtyRegion;
1978         }
1979
1980         mRefreshPending = true;
1981         mFrameLatencyNeeded = true;
1982         if (oldActiveBuffer == NULL) {
1983              // the first time we receive a buffer, we need to trigger a
1984              // geometry invalidation.
1985             recomputeVisibleRegions = true;
1986          }
1987
1988         Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1989         const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1990         const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1991         if ((crop != mCurrentCrop) ||
1992             (transform != mCurrentTransform) ||
1993             (scalingMode != mCurrentScalingMode))
1994         {
1995             mCurrentCrop = crop;
1996             mCurrentTransform = transform;
1997             mCurrentScalingMode = scalingMode;
1998             recomputeVisibleRegions = true;
1999         }
2000
2001         if (oldActiveBuffer != NULL) {
2002             uint32_t bufWidth  = mActiveBuffer->getWidth();
2003             uint32_t bufHeight = mActiveBuffer->getHeight();
2004             if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2005                 bufHeight != uint32_t(oldActiveBuffer->height)) {
2006                 recomputeVisibleRegions = true;
2007             }
2008         }
2009
2010         mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2011         if (oldOpacity != isOpaque(s)) {
2012             recomputeVisibleRegions = true;
2013         }
2014
2015         mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2016
2017         // Remove any sync points corresponding to the buffer which was just
2018         // latched
2019         {
2020             Mutex::Autolock lock(mLocalSyncPointMutex);
2021             auto point = mLocalSyncPoints.begin();
2022             while (point != mLocalSyncPoints.end()) {
2023                 if (!(*point)->frameIsAvailable() ||
2024                         !(*point)->transactionIsApplied()) {
2025                     // This sync point must have been added since we started
2026                     // latching. Don't drop it yet.
2027                     ++point;
2028                     continue;
2029                 }
2030
2031                 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2032                     point = mLocalSyncPoints.erase(point);
2033                 } else {
2034                     ++point;
2035                 }
2036             }
2037         }
2038
2039         // FIXME: postedRegion should be dirty & bounds
2040         Region dirtyRegion(Rect(s.active.w, s.active.h));
2041
2042         // transform the dirty region to window-manager space
2043         outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2044     }
2045     return outDirtyRegion;
2046 }
2047
2048 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2049 {
2050     // TODO: should we do something special if mSecure is set?
2051     if (mProtectedByApp) {
2052         // need a hardware-protected path to external video sink
2053         usage |= GraphicBuffer::USAGE_PROTECTED;
2054     }
2055     if (mPotentialCursor) {
2056         usage |= GraphicBuffer::USAGE_CURSOR;
2057     }
2058     usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2059     return usage;
2060 }
2061
2062 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2063     uint32_t orientation = 0;
2064     if (!mFlinger->mDebugDisableTransformHint) {
2065         // The transform hint is used to improve performance, but we can
2066         // only have a single transform hint, it cannot
2067         // apply to all displays.
2068         const Transform& planeTransform(hw->getTransform());
2069         orientation = planeTransform.getOrientation();
2070         if (orientation & Transform::ROT_INVALID) {
2071             orientation = 0;
2072         }
2073     }
2074     mSurfaceFlingerConsumer->setTransformHint(orientation);
2075 }
2076
2077 // ----------------------------------------------------------------------------
2078 // debugging
2079 // ----------------------------------------------------------------------------
2080
2081 void Layer::dump(String8& result, Colorizer& colorizer) const
2082 {
2083     const Layer::State& s(getDrawingState());
2084
2085     colorizer.colorize(result, Colorizer::GREEN);
2086     result.appendFormat(
2087             "+ %s %p (%s)\n",
2088             getTypeId(), this, getName().string());
2089     colorizer.reset(result);
2090
2091     s.activeTransparentRegion.dump(result, "transparentRegion");
2092     visibleRegion.dump(result, "visibleRegion");
2093     surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2094     sp<Client> client(mClientRef.promote());
2095
2096     result.appendFormat(            "      "
2097             "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2098             "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2099             "isOpaque=%1d, invalidate=%1d, "
2100 #ifdef USE_HWC2
2101             "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2102 #else
2103             "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2104 #endif
2105             "      client=%p\n",
2106             s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2107             s.crop.left, s.crop.top,
2108             s.crop.right, s.crop.bottom,
2109             s.finalCrop.left, s.finalCrop.top,
2110             s.finalCrop.right, s.finalCrop.bottom,
2111             isOpaque(s), contentDirty,
2112             s.alpha, s.flags,
2113             s.active.transform[0][0], s.active.transform[0][1],
2114             s.active.transform[1][0], s.active.transform[1][1],
2115             client.get());
2116
2117     sp<const GraphicBuffer> buf0(mActiveBuffer);
2118     uint32_t w0=0, h0=0, s0=0, f0=0;
2119     if (buf0 != 0) {
2120         w0 = buf0->getWidth();
2121         h0 = buf0->getHeight();
2122         s0 = buf0->getStride();
2123         f0 = buf0->format;
2124     }
2125     result.appendFormat(
2126             "      "
2127             "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2128             " queued-frames=%d, mRefreshPending=%d\n",
2129             mFormat, w0, h0, s0,f0,
2130             mQueuedFrames, mRefreshPending);
2131
2132     if (mSurfaceFlingerConsumer != 0) {
2133         mSurfaceFlingerConsumer->dump(result, "            ");
2134     }
2135 }
2136
2137 void Layer::dumpFrameStats(String8& result) const {
2138     mFrameTracker.dumpStats(result);
2139 }
2140
2141 void Layer::clearFrameStats() {
2142     mFrameTracker.clearStats();
2143 }
2144
2145 void Layer::logFrameStats() {
2146     mFrameTracker.logAndResetStats(mName);
2147 }
2148
2149 void Layer::getFrameStats(FrameStats* outStats) const {
2150     mFrameTracker.getStats(outStats);
2151 }
2152
2153 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2154         bool* outIsGlesComposition, nsecs_t* outPostedTime,
2155         sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2156     *outName = mName;
2157     *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2158
2159 #ifdef USE_HWC2
2160     *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2161             mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2162             HWC2::Composition::Client : true;
2163 #else
2164     *outIsGlesComposition = mIsGlesComposition;
2165 #endif
2166     *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2167     *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2168     *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2169 }
2170 // ---------------------------------------------------------------------------
2171
2172 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2173         const sp<Layer>& layer)
2174     : mFlinger(flinger), mLayer(layer) {
2175 }
2176
2177 Layer::LayerCleaner::~LayerCleaner() {
2178     // destroy client resources
2179     mFlinger->onLayerDestroyed(mLayer);
2180 }
2181
2182 // ---------------------------------------------------------------------------
2183 }; // namespace android
2184
2185 #if defined(__gl_h_)
2186 #error "don't include gl/gl.h in this file"
2187 #endif
2188
2189 #if defined(__gl2_h_)
2190 #error "don't include gl2/gl2.h in this file"
2191 #endif