OSDN Git Service

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