blob: 23c4b303a62b0ca94154a33018634d30af9e5643 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
Mark Salyzyna5e161b2016-09-29 08:08:05 -070031#include <android/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032#include <cutils/properties.h>
33
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070096// This is the phase offset in nanoseconds of the software vsync event
97// relative to the vsync event reported by HWComposer. The software vsync
98// event is when SurfaceFlinger and Choreographer-based applications run each
99// frame.
100//
101// This phase offset allows adjustment of the minimum latency from application
102// wake-up (by Choregographer) time to the time at which the resulting window
103// image is displayed. This value may be either positive (after the HW vsync)
104// or negative (before the HW vsync). Setting it to 0 will result in a
105// minimum latency of two vsync periods because the app and SurfaceFlinger
106// will run just after the HW vsync. Setting it to a positive number will
107// result in the minimum latency being:
108//
109// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
110//
111// Note that reducing this latency makes it more likely for the applications
112// to not have their window content image ready in time. When this happens
113// the latency will end up being an additional vsync period, and animations
114// will hiccup. Therefore, this latency should be tuned somewhat
115// conservatively (or at least with awareness of the trade-off being made).
116static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
117
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700118// This is the phase offset at which SurfaceFlinger's composition runs.
119static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
120
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800121// ---------------------------------------------------------------------------
122
Mathias Agopian99b49842011-06-27 16:05:52 -0700123const String16 sHardwareTest("android.permission.HARDWARE_TEST");
124const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
125const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
126const String16 sDump("android.permission.DUMP");
127
128// ---------------------------------------------------------------------------
129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700131 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700133 mTransactionPending(false),
134 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700135 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700136 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700137 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700153 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800157 mHasColorMatrix(false),
158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
161 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Steve Blocka19954a2012-01-04 20:05:49 +0000163 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164
165 // debugging stuff...
166 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700167
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700169 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700170
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800171 property_get("debug.sf.showupdates", value, "0");
172 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700173
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174 property_get("debug.sf.ddms", value, "0");
175 mDebugDDMS = atoi(value);
176 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700177 if (!startDdmConnection()) {
178 // start failed, and DDMS debugging not enabled
179 mDebugDDMS = 0;
180 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700181 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700182 ALOGI_IF(mDebugRegion, "showupdates enabled");
183 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700184
185 property_get("debug.sf.disable_backpressure", value, "0");
186 mPropagateBackpressure = !atoi(value);
187 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700188
189 property_get("debug.sf.disable_hwc_vds", value, "0");
190 mUseHwcVirtualDisplays = !atoi(value);
191 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800192
193 property_get("ro.sf.disable_triple_buffer", value, "0");
194 mLayerTripleBufferingDisabled = !atoi(value);
195 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196}
197
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800198void SurfaceFlinger::onFirstRef()
199{
200 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800201}
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203SurfaceFlinger::~SurfaceFlinger()
204{
Mathias Agopiana4912602012-07-12 14:25:33 -0700205 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
206 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
207 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208}
209
Dan Stozac7014012014-02-14 15:03:43 -0800210void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800211{
212 // the window manager died on us. prepare its eulogy.
213
Andy McFadden13a082e2012-08-24 10:16:42 -0700214 // restore initial conditions (default device unblank, etc)
215 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800216
217 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700218 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219}
220
Mathias Agopian7e27f052010-05-28 14:22:23 -0700221sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222{
Mathias Agopian96f08192010-06-02 23:28:45 -0700223 sp<ISurfaceComposerClient> bclient;
224 sp<Client> client(new Client(this));
225 status_t err = client->initCheck();
226 if (err == NO_ERROR) {
227 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 return bclient;
230}
231
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700232sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
233 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700234{
235 class DisplayToken : public BBinder {
236 sp<SurfaceFlinger> flinger;
237 virtual ~DisplayToken() {
238 // no more references, this display must be terminated
239 Mutex::Autolock _l(flinger->mStateLock);
240 flinger->mCurrentState.displays.removeItem(this);
241 flinger->setTransactionFlags(eDisplayTransactionNeeded);
242 }
243 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700244 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700245 : flinger(flinger) {
246 }
247 };
248
249 sp<BBinder> token = new DisplayToken(this);
250
251 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700252 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700253 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700254 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700255 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700256 return token;
257}
258
Jesse Hall6c913be2013-08-08 12:15:49 -0700259void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
260 Mutex::Autolock _l(mStateLock);
261
262 ssize_t idx = mCurrentState.displays.indexOfKey(display);
263 if (idx < 0) {
264 ALOGW("destroyDisplay: invalid display token");
265 return;
266 }
267
268 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
269 if (!info.isVirtualDisplay()) {
270 ALOGE("destroyDisplay called for non-virtual display");
271 return;
272 }
Irvelffc9efc2016-07-27 15:16:37 -0700273 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700274 mCurrentState.displays.removeItemsAt(idx);
275 setTransactionFlags(eDisplayTransactionNeeded);
276}
277
Jesse Hall692c7232012-11-08 15:41:56 -0800278void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800279 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800280 ALOGW_IF(mBuiltinDisplays[type],
281 "Overwriting display token for display type %d", type);
282 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800283 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700284 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800285 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700286 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800287}
288
Mathias Agopiane57f2922012-08-09 16:29:12 -0700289sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700290 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
292 return NULL;
293 }
Jesse Hall692c7232012-11-08 15:41:56 -0800294 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295}
296
Jamie Gennis9a78c902011-01-12 18:30:40 -0800297sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
298{
299 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
300 return gba;
301}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303void SurfaceFlinger::bootFinished()
304{
305 const nsecs_t now = systemTime();
306 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000307 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700308 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700309
310 // wait patiently for the window manager death
311 const String16 name("window");
312 sp<IBinder> window(defaultServiceManager()->getService(name));
313 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700314 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700315 }
316
317 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700318 // formerly we would just kill the process, but we now ask it to exit so it
319 // can choose where to stop the animation.
320 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700321
322 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
323 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
324 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325}
326
Mathias Agopian3f844832013-08-07 21:24:32 -0700327void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700328 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700329 RenderEngine& engine;
330 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700331 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700332 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
333 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700334 }
335 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700336 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337 return true;
338 }
339 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700340 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700341}
342
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700343class DispSyncSource : public VSyncSource, private DispSync::Callback {
344public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700345 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346 const char* name) :
347 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700348 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700349 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000350 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
351 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700352 mDispSync(dispSync),
353 mCallbackMutex(),
354 mCallback(),
355 mVsyncMutex(),
356 mPhaseOffset(phaseOffset),
357 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700358
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700359 virtual ~DispSyncSource() {}
360
361 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700362 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000364 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 static_cast<DispSync::Callback*>(this));
366 if (err != NO_ERROR) {
367 ALOGE("error registering vsync callback: %s (%d)",
368 strerror(-err), err);
369 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700370 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700371 } else {
372 status_t err = mDispSync->removeEventListener(
373 static_cast<DispSync::Callback*>(this));
374 if (err != NO_ERROR) {
375 ALOGE("error unregistering vsync callback: %s (%d)",
376 strerror(-err), err);
377 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700378 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 }
382
383 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700384 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700385 mCallback = callback;
386 }
387
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700388 virtual void setPhaseOffset(nsecs_t phaseOffset) {
389 Mutex::Autolock lock(mVsyncMutex);
390
391 // Normalize phaseOffset to [0, period)
392 auto period = mDispSync->getPeriod();
393 phaseOffset %= period;
394 if (phaseOffset < 0) {
395 // If we're here, then phaseOffset is in (-period, 0). After this
396 // operation, it will be in (0, period)
397 phaseOffset += period;
398 }
399 mPhaseOffset = phaseOffset;
400
401 // If we're not enabled, we don't need to mess with the listeners
402 if (!mEnabled) {
403 return;
404 }
405
406 // Remove the listener with the old offset
407 status_t err = mDispSync->removeEventListener(
408 static_cast<DispSync::Callback*>(this));
409 if (err != NO_ERROR) {
410 ALOGE("error unregistering vsync callback: %s (%d)",
411 strerror(-err), err);
412 }
413
414 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
421 }
422
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423private:
424 virtual void onDispSyncEvent(nsecs_t when) {
425 sp<VSyncSource::Callback> callback;
426 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700427 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 callback = mCallback;
429
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700430 if (mTraceVsync) {
431 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700432 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 if (callback != NULL) {
437 callback->onVSyncEvent(when);
438 }
439 }
440
Tim Murray4a4e4a22016-04-19 16:29:23 +0000441 const char* const mName;
442
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 int mValue;
444
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700445 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700446 const String8 mVsyncOnLabel;
447 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700450
451 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453
454 Mutex mVsyncMutex; // Protects the following
455 nsecs_t mPhaseOffset;
456 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700457};
458
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700459class InjectVSyncSource : public VSyncSource {
460public:
461 InjectVSyncSource() {}
462
463 virtual ~InjectVSyncSource() {}
464
465 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
466 std::lock_guard<std::mutex> lock(mCallbackMutex);
467 mCallback = callback;
468 }
469
470 virtual void onInjectSyncEvent(nsecs_t when) {
471 std::lock_guard<std::mutex> lock(mCallbackMutex);
472 mCallback->onVSyncEvent(when);
473 }
474
475 virtual void setVSyncEnabled(bool) {}
476 virtual void setPhaseOffset(nsecs_t) {}
477
478private:
479 std::mutex mCallbackMutex; // Protects the following
480 sp<VSyncSource::Callback> mCallback;
481};
482
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700483void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700484 ALOGI( "SurfaceFlinger's main thread ready to run. "
485 "Initializing graphics H/W...");
486
Dan Stoza9e56aa02015-11-02 13:00:03 -0800487 { // Autolock scope
488 Mutex::Autolock _l(mStateLock);
489
490 // initialize EGL for the default display
491 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
492 eglInitialize(mEGLDisplay, NULL, NULL);
493
494 // start the EventThread
495 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
496 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700497 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800498 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
499 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700500 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800501 mEventQueue.setEventThread(mSFEventThread);
502
Tim Murrayacff43d2016-07-29 13:57:24 -0700503 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700504 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700505 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700506 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
507 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
508 }
509
Dan Stoza9e56aa02015-11-02 13:00:03 -0800510 // Get a RenderEngine for the given display / config (can't fail)
511 mRenderEngine = RenderEngine::create(mEGLDisplay,
512 HAL_PIXEL_FORMAT_RGBA_8888);
513 }
514
515 // Drop the state lock while we initialize the hardware composer. We drop
516 // the lock because on creation, it will call back into SurfaceFlinger to
517 // initialize the primary display.
518 mHwc = new HWComposer(this);
519 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
520
Jesse Hall692c7232012-11-08 15:41:56 -0800521 Mutex::Autolock _l(mStateLock);
522
Mathias Agopian875d8e12013-06-07 15:35:48 -0700523 // retrieve the EGL context that was selected/created
524 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700525
Mathias Agopianda27af92012-09-13 18:17:13 -0700526 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
527 "couldn't create EGLContext");
528
Dan Stoza9e56aa02015-11-02 13:00:03 -0800529 // make the GLContext current so that we can create textures when creating
530 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700531 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
532
Jamie Gennisd1700752013-10-14 12:22:52 -0700533 mEventControlThread = new EventControlThread(this);
534 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
535
Mathias Agopian92a979a2012-08-02 18:32:23 -0700536 // initialize our drawing state
537 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700538
Andy McFadden13a082e2012-08-24 10:16:42 -0700539 // set initial conditions (e.g. unblank default device)
540 initializeDisplays();
541
Dan Stoza4e637772016-07-28 13:31:51 -0700542 mRenderEngine->primeCache();
543
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700544 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700545 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700548}
549
Mathias Agopiana67e4182012-06-19 17:26:12 -0700550void SurfaceFlinger::startBootAnim() {
551 // start boot animation
552 property_set("service.bootanim.exit", "0");
553 property_set("ctl.start", "bootanim");
554}
555
Mathias Agopian875d8e12013-06-07 15:35:48 -0700556size_t SurfaceFlinger::getMaxTextureSize() const {
557 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700558}
559
Mathias Agopian875d8e12013-06-07 15:35:48 -0700560size_t SurfaceFlinger::getMaxViewportDims() const {
561 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700562}
563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800564// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800565
Jamie Gennis582270d2011-08-17 18:19:00 -0700566bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800567 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800568 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800569 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700570 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800571}
572
Brian Anderson069b3652016-07-22 10:32:47 -0700573status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700574 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700575 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700576 FrameEvent::REQUESTED_PRESENT,
577 FrameEvent::ACQUIRE,
578 FrameEvent::FIRST_REFRESH_START,
579 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700580 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700581 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
582 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700583 };
584 return NO_ERROR;
585}
586
Dan Stoza7f7da322014-05-02 15:26:25 -0700587status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
588 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700589 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700590 return BAD_VALUE;
591 }
592
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500593 if (!display.get())
594 return NAME_NOT_FOUND;
595
Jesse Hall692c7232012-11-08 15:41:56 -0800596 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700597 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800598 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700599 type = i;
600 break;
601 }
602 }
603
604 if (type < 0) {
605 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700606 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700607
Mathias Agopian8b736f12012-08-13 17:54:26 -0700608 // TODO: Not sure if display density should handled by SF any longer
609 class Density {
610 static int getDensityFromProperty(char const* propName) {
611 char property[PROPERTY_VALUE_MAX];
612 int density = 0;
613 if (property_get(propName, property, NULL) > 0) {
614 density = atoi(property);
615 }
616 return density;
617 }
618 public:
619 static int getEmuDensity() {
620 return getDensityFromProperty("qemu.sf.lcd_density"); }
621 static int getBuildDensity() {
622 return getDensityFromProperty("ro.sf.lcd_density"); }
623 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700624
Dan Stoza7f7da322014-05-02 15:26:25 -0700625 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700626
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700628 DisplayInfo info = DisplayInfo();
629
Dan Stoza9e56aa02015-11-02 13:00:03 -0800630 float xdpi = hwConfig->getDpiX();
631 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700632
633 if (type == DisplayDevice::DISPLAY_PRIMARY) {
634 // The density of the device is provided by a build property
635 float density = Density::getBuildDensity() / 160.0f;
636 if (density == 0) {
637 // the build doesn't provide a density -- this is wrong!
638 // use xdpi instead
639 ALOGE("ro.sf.lcd_density must be defined as a build property");
640 density = xdpi / 160.0f;
641 }
642 if (Density::getEmuDensity()) {
643 // if "qemu.sf.lcd_density" is specified, it overrides everything
644 xdpi = ydpi = density = Density::getEmuDensity();
645 density /= 160.0f;
646 }
647 info.density = density;
648
649 // TODO: this needs to go away (currently needed only by webkit)
650 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
651 info.orientation = hw->getOrientation();
652 } else {
653 // TODO: where should this value come from?
654 static const int TV_DENSITY = 213;
655 info.density = TV_DENSITY / 160.0f;
656 info.orientation = 0;
657 }
658
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 info.w = hwConfig->getWidth();
660 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700661 info.xdpi = xdpi;
662 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700664 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800665
Andy McFadden91b2ca82014-06-13 14:04:23 -0700666 // This is how far in advance a buffer must be queued for
667 // presentation at a given time. If you want a buffer to appear
668 // on the screen at time N, you must submit the buffer before
669 // (N - presentationDeadline).
670 //
671 // Normally it's one full refresh period (to give SF a chance to
672 // latch the buffer), but this can be reduced by configuring a
673 // DispSync offset. Any additional delays introduced by the hardware
674 // composer or panel must be accounted for here.
675 //
676 // We add an additional 1ms to allow for processing time and
677 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678 info.presentationDeadline = hwConfig->getVsyncPeriod() -
679 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700680
681 // All non-virtual displays are currently considered secure.
682 info.secure = true;
683
Michael Wright28f24d02016-07-12 13:30:53 -0700684 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700685 }
686
Dan Stoza7f7da322014-05-02 15:26:25 -0700687 return NO_ERROR;
688}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700689
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800690status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700691 DisplayStatInfo* stats) {
692 if (stats == NULL) {
693 return BAD_VALUE;
694 }
695
696 // FIXME for now we always return stats for the primary display
697 memset(stats, 0, sizeof(*stats));
698 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
699 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
700 return NO_ERROR;
701}
702
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700703int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800704 if (display == NULL) {
705 ALOGE("%s : display is NULL", __func__);
706 return BAD_VALUE;
707 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700708 sp<DisplayDevice> device(getDisplayDevice(display));
709 if (device != NULL) {
710 return device->getActiveConfig();
711 }
712 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700713}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700714
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700715void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
716 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
717 this);
718 int32_t type = hw->getDisplayType();
719 int currentMode = hw->getActiveConfig();
720
721 if (mode == currentMode) {
722 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
723 return;
724 }
725
726 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
727 ALOGW("Trying to set config for virtual display");
728 return;
729 }
730
731 hw->setActiveConfig(mode);
732 getHwComposer().setActiveConfig(type, mode);
733}
734
735status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
736 class MessageSetActiveConfig: public MessageBase {
737 SurfaceFlinger& mFlinger;
738 sp<IBinder> mDisplay;
739 int mMode;
740 public:
741 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
742 int mode) :
743 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
744 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700745 Vector<DisplayInfo> configs;
746 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700747 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700748 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700749 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700750 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700751 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700752 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
753 if (hw == NULL) {
754 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700755 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700756 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
757 ALOGW("Attempt to set active config = %d for virtual display",
758 mMode);
759 } else {
760 mFlinger.setActiveConfigInternal(hw, mMode);
761 }
762 return true;
763 }
764 };
765 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
766 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700767 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700768}
Michael Wright28f24d02016-07-12 13:30:53 -0700769status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
770 Vector<android_color_mode_t>* outColorModes) {
771 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
772 return BAD_VALUE;
773 }
774
775 if (!display.get()) {
776 return NAME_NOT_FOUND;
777 }
778
779 int32_t type = NAME_NOT_FOUND;
780 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
781 if (display == mBuiltinDisplays[i]) {
782 type = i;
783 break;
784 }
785 }
786
787 if (type < 0) {
788 return type;
789 }
790
791 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
792 outColorModes->clear();
793 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
794
795 return NO_ERROR;
796}
797
798android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
799 sp<DisplayDevice> device(getDisplayDevice(display));
800 if (device != nullptr) {
801 return device->getActiveColorMode();
802 }
803 return static_cast<android_color_mode_t>(BAD_VALUE);
804}
805
806void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
807 android_color_mode_t mode) {
808 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
809 this);
810 int32_t type = hw->getDisplayType();
811 android_color_mode_t currentMode = hw->getActiveColorMode();
812
813 if (mode == currentMode) {
814 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
815 return;
816 }
817
818 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
819 ALOGW("Trying to set config for virtual display");
820 return;
821 }
822
823 hw->setActiveColorMode(mode);
824 getHwComposer().setActiveColorMode(type, mode);
825}
826
827
828status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
829 android_color_mode_t colorMode) {
830 class MessageSetActiveColorMode: public MessageBase {
831 SurfaceFlinger& mFlinger;
832 sp<IBinder> mDisplay;
833 android_color_mode_t mMode;
834 public:
835 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
836 android_color_mode_t mode) :
837 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
838 virtual bool handler() {
839 Vector<android_color_mode_t> modes;
840 mFlinger.getDisplayColorModes(mDisplay, &modes);
841 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
842 if (mMode < 0 || !exists) {
843 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
844 mDisplay.get());
845 return true;
846 }
847 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
848 if (hw == nullptr) {
849 ALOGE("Attempt to set active color mode = %d for null display %p",
850 mMode, mDisplay.get());
851 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
852 ALOGW("Attempt to set active color mode= %d for virtual display",
853 mMode);
854 } else {
855 mFlinger.setActiveColorModeInternal(hw, mMode);
856 }
857 return true;
858 }
859 };
860 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
861 postMessageSync(msg);
862 return NO_ERROR;
863}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700864
Svetoslavd85084b2014-03-20 10:28:31 -0700865status_t SurfaceFlinger::clearAnimationFrameStats() {
866 Mutex::Autolock _l(mStateLock);
867 mAnimFrameTracker.clearStats();
868 return NO_ERROR;
869}
870
871status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
872 Mutex::Autolock _l(mStateLock);
873 mAnimFrameTracker.getStats(outStats);
874 return NO_ERROR;
875}
876
Dan Stozac4f471e2016-03-24 09:31:08 -0700877status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
878 HdrCapabilities* outCapabilities) const {
879 Mutex::Autolock _l(mStateLock);
880
881 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
882 if (displayDevice == nullptr) {
883 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
884 return BAD_VALUE;
885 }
886
887 std::unique_ptr<HdrCapabilities> capabilities =
888 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
889 if (capabilities) {
890 std::swap(*outCapabilities, *capabilities);
891 } else {
892 return BAD_VALUE;
893 }
894
895 return NO_ERROR;
896}
897
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700898status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
899 if (enable == mInjectVSyncs) {
900 return NO_ERROR;
901 }
902
903 if (enable) {
904 mInjectVSyncs = enable;
905 ALOGV("VSync Injections enabled");
906 if (mVSyncInjector.get() == nullptr) {
907 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700908 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700909 }
910 mEventQueue.setEventThread(mInjectorEventThread);
911 } else {
912 mInjectVSyncs = enable;
913 ALOGV("VSync Injections disabled");
914 mEventQueue.setEventThread(mSFEventThread);
915 mVSyncInjector.clear();
916 }
917 return NO_ERROR;
918}
919
920status_t SurfaceFlinger::injectVSync(nsecs_t when) {
921 if (!mInjectVSyncs) {
922 ALOGE("VSync Injections not enabled");
923 return BAD_VALUE;
924 }
925 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
926 ALOGV("Injecting VSync inside SurfaceFlinger");
927 mVSyncInjector->onInjectSyncEvent(when);
928 }
929 return NO_ERROR;
930}
931
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800932// ----------------------------------------------------------------------------
933
934sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800935 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700936}
937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800938// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800939
940void SurfaceFlinger::waitForEvent() {
941 mEventQueue.waitMessage();
942}
943
944void SurfaceFlinger::signalTransaction() {
945 mEventQueue.invalidate();
946}
947
948void SurfaceFlinger::signalLayerUpdate() {
949 mEventQueue.invalidate();
950}
951
952void SurfaceFlinger::signalRefresh() {
953 mEventQueue.refresh();
954}
955
956status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800957 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800958 return mEventQueue.postMessage(msg, reltime);
959}
960
961status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800962 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800963 status_t res = mEventQueue.postMessage(msg, reltime);
964 if (res == NO_ERROR) {
965 msg->wait();
966 }
967 return res;
968}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800969
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700970void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700971 do {
972 waitForEvent();
973 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800974}
975
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700976void SurfaceFlinger::enableHardwareVsync() {
977 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700978 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700979 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700980 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
981 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700982 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700983 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700984}
985
Jesse Hall948fe0c2013-10-14 12:56:09 -0700986void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700987 Mutex::Autolock _l(mHWVsyncLock);
988
Jesse Hall948fe0c2013-10-14 12:56:09 -0700989 if (makeAvailable) {
990 mHWVsyncAvailable = true;
991 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700992 // Hardware vsync is not currently available, so abort the resync
993 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700994 return;
995 }
996
Dan Stoza9e56aa02015-11-02 13:00:03 -0800997 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
998 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700999
1000 mPrimaryDispSync.reset();
1001 mPrimaryDispSync.setPeriod(period);
1002
1003 if (!mPrimaryHWVsyncEnabled) {
1004 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001005 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1006 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001007 mPrimaryHWVsyncEnabled = true;
1008 }
1009}
1010
Jesse Hall948fe0c2013-10-14 12:56:09 -07001011void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001012 Mutex::Autolock _l(mHWVsyncLock);
1013 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001014 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1015 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001016 mPrimaryDispSync.endResync();
1017 mPrimaryHWVsyncEnabled = false;
1018 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001019 if (makeUnavailable) {
1020 mHWVsyncAvailable = false;
1021 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001022}
1023
Tim Murray4a4e4a22016-04-19 16:29:23 +00001024void SurfaceFlinger::resyncWithRateLimit() {
1025 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1026 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001027 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001028 }
1029}
1030
Dan Stoza9e56aa02015-11-02 13:00:03 -08001031void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001032 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001033
Jamie Gennisd1700752013-10-14 12:22:52 -07001034 { // Scope for the lock
1035 Mutex::Autolock _l(mHWVsyncLock);
1036 if (type == 0 && mPrimaryHWVsyncEnabled) {
1037 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001038 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001039 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001040
1041 if (needsHwVsync) {
1042 enableHardwareVsync();
1043 } else {
1044 disableHardwareVsync(false);
1045 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001046}
1047
Dan Stoza9e56aa02015-11-02 13:00:03 -08001048void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1049 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1050 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1051 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001052
Dan Stoza9e56aa02015-11-02 13:00:03 -08001053 // All non-virtual displays are currently considered secure.
1054 bool isSecure = true;
1055
1056 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1057 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1058 wp<IBinder> token = mBuiltinDisplays[type];
1059
1060 sp<IGraphicBufferProducer> producer;
1061 sp<IGraphicBufferConsumer> consumer;
1062 BufferQueue::createBufferQueue(&producer, &consumer,
1063 new GraphicBufferAlloc());
1064
1065 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1066 DisplayDevice::DISPLAY_PRIMARY, consumer);
1067 sp<DisplayDevice> hw = new DisplayDevice(this,
1068 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1069 producer, mRenderEngine->getEGLConfig());
1070 mDisplays.add(token, hw);
1071 } else {
1072 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001073 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001074 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001075 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001076 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001077 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1078 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001079 }
1080 setTransactionFlags(eDisplayTransactionNeeded);
1081
Andy McFadden9e9689c2012-10-10 18:17:51 -07001082 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001083 }
Mathias Agopian86303202012-07-24 22:46:10 -07001084}
1085
Dan Stoza9e56aa02015-11-02 13:00:03 -08001086void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001088 getHwComposer().setVsyncEnabled(disp,
1089 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001090}
1091
Mathias Agopian4fec8732012-06-29 14:12:52 -07001092void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001093 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001094 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001095 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001096 bool frameMissed = !mHadClientComposition &&
1097 mPreviousPresentFence != Fence::NO_FENCE &&
1098 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1099 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001100 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001101 signalLayerUpdate();
1102 break;
1103 }
1104
Dan Stoza6b9454d2014-11-07 16:00:59 -08001105 bool refreshNeeded = handleMessageTransaction();
1106 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001107 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001108 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001109 // Signal a refresh if a transaction modified the window state,
1110 // a new buffer was latched, or if HWC has requested a full
1111 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001112 signalRefresh();
1113 }
1114 break;
1115 }
1116 case MessageQueue::REFRESH: {
1117 handleMessageRefresh();
1118 break;
1119 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001120 }
1121}
1122
Dan Stoza6b9454d2014-11-07 16:00:59 -08001123bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001124 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001125 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001126 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001127 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001128 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001129 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001130}
1131
Dan Stoza6b9454d2014-11-07 16:00:59 -08001132bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001133 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001134 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001135}
1136
1137void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001138 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001139
Pablo Ceballos40845df2016-01-25 17:41:15 -08001140 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001141
Brian Andersond6927fb2016-07-23 23:37:30 -07001142 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001143 rebuildLayerStacks();
1144 setUpHWComposer();
1145 doDebugFlashRegions();
1146 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001147 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001148
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001149 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001150
1151 mHadClientComposition = false;
1152 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1153 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1154 mHadClientComposition = mHadClientComposition ||
1155 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1156 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001157
Dan Stoza9e56aa02015-11-02 13:00:03 -08001158 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001159}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001160
Mathias Agopiancd60f992012-08-16 16:28:27 -07001161void SurfaceFlinger::doDebugFlashRegions()
1162{
1163 // is debugging enabled
1164 if (CC_LIKELY(!mDebugRegion))
1165 return;
1166
1167 const bool repaintEverything = mRepaintEverything;
1168 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1169 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001170 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001171 // transform the dirty region into this screen's coordinate space
1172 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1173 if (!dirtyRegion.isEmpty()) {
1174 // redraw the whole screen
1175 doComposeSurfaces(hw, Region(hw->bounds()));
1176
1177 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001178 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001179 RenderEngine& engine(getRenderEngine());
1180 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1181
Mathias Agopianda27af92012-09-13 18:17:13 -07001182 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001183 }
1184 }
1185 }
1186
1187 postFramebuffer();
1188
1189 if (mDebugRegion > 1) {
1190 usleep(mDebugRegion * 1000);
1191 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001192
Dan Stoza9e56aa02015-11-02 13:00:03 -08001193 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001194 auto& displayDevice = mDisplays[displayId];
1195 if (!displayDevice->isDisplayOn()) {
1196 continue;
1197 }
1198
1199 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1201 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001202 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001203}
1204
Brian Andersond6927fb2016-07-23 23:37:30 -07001205void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001206{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 ATRACE_CALL();
1208 ALOGV("preComposition");
1209
Mathias Agopiancd60f992012-08-16 16:28:27 -07001210 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001211 const LayerVector& layers(mDrawingState.layersSortedByZ);
1212 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001213 for (size_t i=0 ; i<count ; i++) {
Brian Andersond6927fb2016-07-23 23:37:30 -07001214 if (layers[i]->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001215 needExtraInvalidate = true;
1216 }
1217 }
1218 if (needExtraInvalidate) {
1219 signalLayerUpdate();
1220 }
1221}
1222
Brian Andersond6927fb2016-07-23 23:37:30 -07001223void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001224{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001225 ATRACE_CALL();
1226 ALOGV("postComposition");
1227
Brian Anderson3546a3f2016-07-14 11:51:14 -07001228 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001229 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001230 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001231 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001232 }
1233
Brian Andersond6927fb2016-07-23 23:37:30 -07001234 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001235
1236 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1237 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1238 glCompositionDoneFenceTime =
1239 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1240 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1241 } else {
1242 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1243 }
1244 mGlCompositionDoneTimeline.updateSignalTimes();
1245
1246 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1247 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1248 mDisplayTimeline.push(displayFenceTime);
1249 mDisplayTimeline.updateSignalTimes();
1250
1251 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1252 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1253 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1254 presentFenceTime = &displayFenceTime;
1255 } else {
1256 retireFenceTime = &displayFenceTime;
1257 }
1258
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001259 const LayerVector& layers(mDrawingState.layersSortedByZ);
1260 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001261 for (size_t i=0 ; i<count ; i++) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001262 bool frameLatched =
1263 layers[i]->onPostComposition(glCompositionDoneFenceTime,
1264 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001265 if (frameLatched) {
1266 recordBufferingStats(layers[i]->getName().string(),
1267 layers[i]->getOccupancyHistory(false));
1268 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001269 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001270
Brian Anderson3d4039d2016-09-23 16:31:30 -07001271 if (displayFence->isValid()) {
1272 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273 enableHardwareVsync();
1274 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001275 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276 }
1277 }
1278
Andy McFadden5167ec62014-05-22 13:08:43 -07001279 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001280 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001281 enableHardwareVsync();
1282 }
1283 }
1284
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001285 if (mAnimCompositionPending) {
1286 mAnimCompositionPending = false;
1287
Brian Anderson3d4039d2016-09-23 16:31:30 -07001288 if (displayFenceTime->isValid()) {
1289 mAnimFrameTracker.setActualPresentFence(
1290 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001291 } else {
1292 // The HWC doesn't support present fences, so use the refresh
1293 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001294 nsecs_t presentTime =
1295 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001296 mAnimFrameTracker.setActualPresentTime(presentTime);
1297 }
1298 mAnimFrameTracker.advanceFrame();
1299 }
Dan Stozab90cf072015-03-05 11:05:59 -08001300
1301 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1302 return;
1303 }
1304
1305 nsecs_t currentTime = systemTime();
1306 if (mHasPoweredOff) {
1307 mHasPoweredOff = false;
1308 } else {
1309 nsecs_t period = mPrimaryDispSync.getPeriod();
1310 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1311 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1312 if (numPeriods < NUM_BUCKETS - 1) {
1313 mFrameBuckets[numPeriods] += elapsedTime;
1314 } else {
1315 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1316 }
1317 mTotalTime += elapsedTime;
1318 }
1319 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001320}
1321
1322void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001323 ATRACE_CALL();
1324 ALOGV("rebuildLayerStacks");
1325
Mathias Agopiancd60f992012-08-16 16:28:27 -07001326 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001327 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001328 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001329 mVisibleRegionsDirty = false;
1330 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001331
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001332 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001333 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001334 Region opaqueRegion;
1335 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001336 Vector<sp<Layer>> layersSortedByZ;
1337 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1338 const Transform& tr(displayDevice->getTransform());
1339 const Rect bounds(displayDevice->getBounds());
1340 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001341 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 displayDevice->getLayerStack(), dirtyRegion,
1343 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001344
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001345 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001346 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001347 const sp<Layer>& layer(layers[i]);
1348 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001350 Region drawRegion(tr.transform(
1351 layer->visibleNonTransparentRegion));
1352 drawRegion.andSelf(bounds);
1353 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001354 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001355 } else {
1356 // Clear out the HWC layer if this layer was
1357 // previously visible, but no longer is
1358 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1359 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001360 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001361 }
1362 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001363 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001364 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1365 displayDevice->undefinedRegion.set(bounds);
1366 displayDevice->undefinedRegion.subtractSelf(
1367 tr.transform(opaqueRegion));
1368 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001369 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001370 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001371}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001372
Mathias Agopiancd60f992012-08-16 16:28:27 -07001373void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 ATRACE_CALL();
1375 ALOGV("setUpHWComposer");
1376
Jesse Hall028dc8f2013-08-20 16:35:32 -07001377 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001378 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1379 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1380 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1381
1382 // If nothing has changed (!dirty), don't recompose.
1383 // If something changed, but we don't currently have any visible layers,
1384 // and didn't when we last did a composition, then skip it this time.
1385 // The second rule does two things:
1386 // - When all layers are removed from a display, we'll emit one black
1387 // frame, then nothing more until we get new layers.
1388 // - When a display is created with a private layer stack, we won't
1389 // emit any black frames until a layer is added to the layer stack.
1390 bool mustRecompose = dirty && !(empty && wasEmpty);
1391
1392 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1393 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1394 mustRecompose ? "doing" : "skipping",
1395 dirty ? "+" : "-",
1396 empty ? "+" : "-",
1397 wasEmpty ? "+" : "-");
1398
Dan Stoza71433162014-02-04 16:22:36 -08001399 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001400
1401 if (mustRecompose) {
1402 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1403 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001404 }
1405
Dan Stoza9e56aa02015-11-02 13:00:03 -08001406 // build the h/w work list
1407 if (CC_UNLIKELY(mGeometryInvalid)) {
1408 mGeometryInvalid = false;
1409 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1410 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1411 const auto hwcId = displayDevice->getHwcDisplayId();
1412 if (hwcId >= 0) {
1413 const Vector<sp<Layer>>& currentLayers(
1414 displayDevice->getVisibleLayersSortedByZ());
1415 bool foundLayerWithoutHwc = false;
1416 for (auto& layer : currentLayers) {
1417 if (!layer->hasHwcLayer(hwcId)) {
1418 auto hwcLayer = mHwc->createLayer(hwcId);
1419 if (hwcLayer) {
1420 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1421 } else {
1422 layer->forceClientComposition(hwcId);
1423 foundLayerWithoutHwc = true;
1424 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001425 }
1426 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001427
Dan Stoza9e56aa02015-11-02 13:00:03 -08001428 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001429 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001431 }
1432 }
1433 }
1434 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001435 }
Riley Andrews03414a12014-07-01 14:22:59 -07001436
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001437
1438 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1439
Dan Stoza9e56aa02015-11-02 13:00:03 -08001440 // Set the per-frame data
1441 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1442 auto& displayDevice = mDisplays[displayId];
1443 const auto hwcId = displayDevice->getHwcDisplayId();
1444 if (hwcId < 0) {
1445 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001446 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001447 if (colorMatrix != mPreviousColorMatrix) {
1448 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1449 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1450 "display %zd: %d", displayId, result);
1451 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001452 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1453 layer->setPerFrameData(displayDevice);
1454 }
1455 }
1456
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001457 mPreviousColorMatrix = colorMatrix;
1458
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001460 auto& displayDevice = mDisplays[displayId];
1461 if (!displayDevice->isDisplayOn()) {
1462 continue;
1463 }
1464
1465 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001466 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1467 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001468 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001469}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001470
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471void SurfaceFlinger::doComposition() {
1472 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 ALOGV("doComposition");
1474
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001475 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001476 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001477 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001478 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 // transform the dirty region into this screen's coordinate space
1480 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001481
1482 // repaint the framebuffer (if needed)
1483 doDisplayComposition(hw, dirtyRegion);
1484
Mathias Agopiancd60f992012-08-16 16:28:27 -07001485 hw->dirtyRegion.clear();
1486 hw->flip(hw->swapRegion);
1487 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001488 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001489 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001490 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001491}
1492
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493void SurfaceFlinger::postFramebuffer()
1494{
Mathias Agopian841cde52012-03-01 15:44:37 -08001495 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001497
Mathias Agopiana44b0412011-10-16 18:46:35 -07001498 const nsecs_t now = systemTime();
1499 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001500
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1502 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001503 if (!displayDevice->isDisplayOn()) {
1504 continue;
1505 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 const auto hwcId = displayDevice->getHwcDisplayId();
1507 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001508 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001509 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001510 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001511 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001512 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1513 sp<Fence> releaseFence = Fence::NO_FENCE;
1514 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1515 releaseFence = displayDevice->getClientTargetAcquireFence();
1516 } else {
1517 auto hwcLayer = layer->getHwcLayer(hwcId);
1518 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001519 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 layer->onLayerDisplayed(releaseFence);
1521 }
1522 if (hwcId >= 0) {
1523 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001524 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001525 }
1526
Mathias Agopiana44b0412011-10-16 18:46:35 -07001527 mLastSwapBufferTime = systemTime() - now;
1528 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001529
1530 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1531 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1532 logFrameStats();
1533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001534}
1535
Mathias Agopian87baae12012-07-31 12:38:26 -07001536void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001537{
Mathias Agopian841cde52012-03-01 15:44:37 -08001538 ATRACE_CALL();
1539
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001540 // here we keep a copy of the drawing state (that is the state that's
1541 // going to be overwritten by handleTransactionLocked()) outside of
1542 // mStateLock so that the side-effects of the State assignment
1543 // don't happen with mStateLock held (which can cause deadlocks).
1544 State drawingState(mDrawingState);
1545
Mathias Agopianca4d3602011-05-19 15:38:14 -07001546 Mutex::Autolock _l(mStateLock);
1547 const nsecs_t now = systemTime();
1548 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001549
Mathias Agopianca4d3602011-05-19 15:38:14 -07001550 // Here we're guaranteed that some transaction flags are set
1551 // so we can call handleTransactionLocked() unconditionally.
1552 // We call getTransactionFlags(), which will also clear the flags,
1553 // with mStateLock held to guarantee that mCurrentState won't change
1554 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001555
Mathias Agopiane57f2922012-08-09 16:29:12 -07001556 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001557 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001558
Mathias Agopianca4d3602011-05-19 15:38:14 -07001559 mLastTransactionTime = systemTime() - now;
1560 mDebugInTransaction = 0;
1561 invalidateHwcGeometry();
1562 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001563}
1564
Mathias Agopian87baae12012-07-31 12:38:26 -07001565void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001566{
1567 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001568 const size_t count = currentLayers.size();
1569
Dan Stoza7dde5992015-05-22 09:51:44 -07001570 // Notify all layers of available frames
1571 for (size_t i = 0; i < count; ++i) {
1572 currentLayers[i]->notifyAvailableFrames();
1573 }
1574
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001575 /*
1576 * Traversal of the children
1577 * (perform the transaction for each of them if needed)
1578 */
1579
Mathias Agopian3559b072012-08-15 13:46:03 -07001580 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001582 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001583 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1584 if (!trFlags) continue;
1585
1586 const uint32_t flags = layer->doTransaction(0);
1587 if (flags & Layer::eVisibleRegion)
1588 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001589 }
1590 }
1591
1592 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001593 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001594 */
1595
Mathias Agopiane57f2922012-08-09 16:29:12 -07001596 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001597 // here we take advantage of Vector's copy-on-write semantics to
1598 // improve performance by skipping the transaction entirely when
1599 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001600 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1601 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001602 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001603 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001604 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001605 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001606
1607 // find the displays that were removed
1608 // (ie: in drawing state but not in current state)
1609 // also handle displays that changed
1610 // (ie: displays that are in both lists)
1611 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001612 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1613 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001614 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001615 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001616 // Call makeCurrent() on the primary display so we can
1617 // be sure that nothing associated with this display
1618 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001619 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001620 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001621 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1622 if (hw != NULL)
1623 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001624 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001625 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001626 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001627 } else {
1628 ALOGW("trying to remove the main display");
1629 }
1630 } else {
1631 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001632 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001633 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001634 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1635 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001636 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001637 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001638 // recreating the DisplayDevice, so we just remove it
1639 // from the drawing state, so that it get re-added
1640 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001641 sp<DisplayDevice> hw(getDisplayDevice(display));
1642 if (hw != NULL)
1643 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001644 mDisplays.removeItem(display);
1645 mDrawingState.displays.removeItemsAt(i);
1646 dc--; i--;
1647 // at this point we must loop to the next item
1648 continue;
1649 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001650
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001651 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001652 if (disp != NULL) {
1653 if (state.layerStack != draw[i].layerStack) {
1654 disp->setLayerStack(state.layerStack);
1655 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001656 if ((state.orientation != draw[i].orientation)
1657 || (state.viewport != draw[i].viewport)
1658 || (state.frame != draw[i].frame))
1659 {
1660 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001661 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001662 }
Michael Lentine47e45402014-07-18 15:34:25 -07001663 if (state.width != draw[i].width || state.height != draw[i].height) {
1664 disp->setDisplaySize(state.width, state.height);
1665 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001666 }
1667 }
1668 }
1669
1670 // find displays that were added
1671 // (ie: in current state but not in drawing state)
1672 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001673 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001674 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001675
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001676 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001677 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001678 sp<IGraphicBufferProducer> bqProducer;
1679 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001680 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1681 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001682
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001684 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001685 // Virtual displays without a surface are dormant:
1686 // they have external state (layer stack, projection,
1687 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001688 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001689
Dan Stoza8cf150a2016-08-02 10:27:31 -07001690 if (mUseHwcVirtualDisplays) {
1691 int width = 0;
1692 int status = state.surface->query(
1693 NATIVE_WINDOW_WIDTH, &width);
1694 ALOGE_IF(status != NO_ERROR,
1695 "Unable to query width (%d)", status);
1696 int height = 0;
1697 status = state.surface->query(
1698 NATIVE_WINDOW_HEIGHT, &height);
1699 ALOGE_IF(status != NO_ERROR,
1700 "Unable to query height (%d)", status);
1701 int intFormat = 0;
1702 status = state.surface->query(
1703 NATIVE_WINDOW_FORMAT, &intFormat);
1704 ALOGE_IF(status != NO_ERROR,
1705 "Unable to query format (%d)", status);
1706 auto format = static_cast<android_pixel_format_t>(
1707 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001708
Dan Stoza8cf150a2016-08-02 10:27:31 -07001709 mHwc->allocateVirtualDisplay(width, height, &format,
1710 &hwcId);
1711 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712
Dan Stoza5cf424b2016-05-20 14:02:39 -07001713 // TODO: Plumb requested format back up to consumer
1714
Dan Stoza9e56aa02015-11-02 13:00:03 -08001715 sp<VirtualDisplaySurface> vds =
1716 new VirtualDisplaySurface(*mHwc,
1717 hwcId, state.surface, bqProducer,
1718 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001719
1720 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001721 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001722 }
1723 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001724 ALOGE_IF(state.surface!=NULL,
1725 "adding a supported display, but rendering "
1726 "surface is provided (%p), ignoring it",
1727 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1729 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1730 dispSurface = new FramebufferSurface(*mHwc,
1731 DisplayDevice::DISPLAY_EXTERNAL,
1732 bqConsumer);
1733 producer = bqProducer;
1734 } else {
1735 ALOGE("Attempted to add non-external non-virtual"
1736 " display");
1737 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001738 }
1739
1740 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001741 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001742 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 state.type, hwcId, state.isSecure, display,
1744 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001745 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001746 hw->setLayerStack(state.layerStack);
1747 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001748 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001749 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001750 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001752 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001753 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001754 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001755 }
1756 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001757 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001758 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001759
Mathias Agopian84300952012-11-21 16:02:13 -08001760 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1761 // The transform hint might have changed for some layers
1762 // (either because a display has changed, or because a layer
1763 // as changed).
1764 //
1765 // Walk through all the layers in currentLayers,
1766 // and update their transform hint.
1767 //
1768 // If a layer is visible only on a single display, then that
1769 // display is used to calculate the hint, otherwise we use the
1770 // default display.
1771 //
1772 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1773 // the hint is set before we acquire a buffer from the surface texture.
1774 //
1775 // NOTE: layer transactions have taken place already, so we use their
1776 // drawing state. However, SurfaceFlinger's own transaction has not
1777 // happened yet, so we must use the current state layer list
1778 // (soon to become the drawing state list).
1779 //
1780 sp<const DisplayDevice> disp;
1781 uint32_t currentlayerStack = 0;
1782 for (size_t i=0; i<count; i++) {
1783 // NOTE: we rely on the fact that layers are sorted by
1784 // layerStack first (so we don't have to traverse the list
1785 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001786 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001787 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001788 if (i==0 || currentlayerStack != layerStack) {
1789 currentlayerStack = layerStack;
1790 // figure out if this layerstack is mirrored
1791 // (more than one display) if so, pick the default display,
1792 // if not, pick the only display it's on.
1793 disp.clear();
1794 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1795 sp<const DisplayDevice> hw(mDisplays[dpy]);
1796 if (hw->getLayerStack() == currentlayerStack) {
1797 if (disp == NULL) {
1798 disp = hw;
1799 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001800 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001801 break;
1802 }
1803 }
1804 }
1805 }
Chet Haase91d25932013-04-11 15:24:55 -07001806 if (disp == NULL) {
1807 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1808 // redraw after transform hint changes. See bug 8508397.
1809
1810 // could be null when this layer is using a layerStack
1811 // that is not visible on any display. Also can occur at
1812 // screen off/on times.
1813 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001814 }
Chet Haase91d25932013-04-11 15:24:55 -07001815 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001816 }
1817 }
1818
1819
Mathias Agopian3559b072012-08-15 13:46:03 -07001820 /*
1821 * Perform our own transaction if needed
1822 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001823
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001824 const LayerVector& layers(mDrawingState.layersSortedByZ);
1825 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001826 // layers have been added
1827 mVisibleRegionsDirty = true;
1828 }
1829
1830 // some layers might have been removed, so
1831 // we need to update the regions they're exposing.
1832 if (mLayersRemoved) {
1833 mLayersRemoved = false;
1834 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001835 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001836 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001837 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001838 if (currentLayers.indexOf(layer) < 0) {
1839 // this layer is not visible anymore
1840 // TODO: we could traverse the tree from front to back and
1841 // compute the actual visible region
1842 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001843 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001844 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001845 Region(Rect(s.active.w, s.active.h)));
1846 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001847 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001849 }
1850
1851 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001852
1853 updateCursorAsync();
1854}
1855
1856void SurfaceFlinger::updateCursorAsync()
1857{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1859 auto& displayDevice = mDisplays[displayId];
1860 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001861 continue;
1862 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863
1864 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1865 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001866 }
1867 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001868}
1869
1870void SurfaceFlinger::commitTransaction()
1871{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001872 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001873 // Notify removed layers now that they can't be drawn from
1874 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001875 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1876 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001877 mLayersPendingRemoval[i]->onRemoved();
1878 }
1879 mLayersPendingRemoval.clear();
1880 }
1881
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001882 // If this transaction is part of a window animation then the next frame
1883 // we composite should be considered an animation as well.
1884 mAnimCompositionPending = mAnimTransactionPending;
1885
Mathias Agopian4fec8732012-06-29 14:12:52 -07001886 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001887 mTransactionPending = false;
1888 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001889 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001890}
1891
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001892void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001893 const LayerVector& currentLayers, uint32_t layerStack,
1894 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001895{
Mathias Agopian841cde52012-03-01 15:44:37 -08001896 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001898
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 Region aboveOpaqueLayers;
1900 Region aboveCoveredLayers;
1901 Region dirty;
1902
Mathias Agopian87baae12012-07-31 12:38:26 -07001903 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001904
1905 size_t i = currentLayers.size();
1906 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001907 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908
1909 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001910 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911
Jesse Hall01e29052013-02-19 16:13:35 -08001912 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001913 if (s.layerStack != layerStack)
1914 continue;
1915
Mathias Agopianab028732010-03-16 16:41:46 -07001916 /*
1917 * opaqueRegion: area of a surface that is fully opaque.
1918 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001919 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001920
1921 /*
1922 * visibleRegion: area of a surface that is visible on screen
1923 * and not fully transparent. This is essentially the layer's
1924 * footprint minus the opaque regions above it.
1925 * Areas covered by a translucent surface are considered visible.
1926 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001927 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001928
1929 /*
1930 * coveredRegion: area of a surface that is covered by all
1931 * visible regions above it (which includes the translucent areas).
1932 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001933 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001934
Jesse Halla8026d22012-09-25 13:25:04 -07001935 /*
1936 * transparentRegion: area of a surface that is hinted to be completely
1937 * transparent. This is only used to tell when the layer has no visible
1938 * non-transparent regions and can be removed from the layer list. It
1939 * does not affect the visibleRegion of this layer or any layers
1940 * beneath it. The hint may not be correct if apps don't respect the
1941 * SurfaceView restrictions (which, sadly, some don't).
1942 */
1943 Region transparentRegion;
1944
Mathias Agopianab028732010-03-16 16:41:46 -07001945
1946 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001947 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001948 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001949 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001950 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001951 if (!visibleRegion.isEmpty()) {
1952 // Remove the transparent area from the visible region
1953 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001954 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001955 if (tr.preserveRects()) {
1956 // transform the transparent region
1957 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001958 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001959 // transformation too complex, can't do the
1960 // transparent region optimization.
1961 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962 }
Mathias Agopianab028732010-03-16 16:41:46 -07001963 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001964
Mathias Agopianab028732010-03-16 16:41:46 -07001965 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001966 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001968 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1969 // the opaque region is the layer's footprint
1970 opaqueRegion = visibleRegion;
1971 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001972 }
1973 }
1974
Mathias Agopianab028732010-03-16 16:41:46 -07001975 // Clip the covered region to the visible region
1976 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1977
1978 // Update aboveCoveredLayers for next (lower) layer
1979 aboveCoveredLayers.orSelf(visibleRegion);
1980
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981 // subtract the opaque region covered by the layers above us
1982 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983
1984 // compute this layer's dirty region
1985 if (layer->contentDirty) {
1986 // we need to invalidate the whole region
1987 dirty = visibleRegion;
1988 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001989 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990 layer->contentDirty = false;
1991 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001992 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001993 * the exposed region consists of two components:
1994 * 1) what's VISIBLE now and was COVERED before
1995 * 2) what's EXPOSED now less what was EXPOSED before
1996 *
1997 * note that (1) is conservative, we start with the whole
1998 * visible region but only keep what used to be covered by
1999 * something -- which mean it may have been exposed.
2000 *
2001 * (2) handles areas that were not covered by anything but got
2002 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002003 */
Mathias Agopianab028732010-03-16 16:41:46 -07002004 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002005 const Region oldVisibleRegion = layer->visibleRegion;
2006 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002007 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2008 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009 }
2010 dirty.subtractSelf(aboveOpaqueLayers);
2011
2012 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002013 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002014
Mathias Agopianab028732010-03-16 16:41:46 -07002015 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002017
Jesse Halla8026d22012-09-25 13:25:04 -07002018 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002019 layer->setVisibleRegion(visibleRegion);
2020 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002021 layer->setVisibleNonTransparentRegion(
2022 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 }
2024
Mathias Agopian87baae12012-07-31 12:38:26 -07002025 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002026}
2027
Mathias Agopian87baae12012-07-31 12:38:26 -07002028void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2029 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002030 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002031 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2032 if (hw->getLayerStack() == layerStack) {
2033 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002034 }
2035 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002036}
2037
Dan Stoza6b9454d2014-11-07 16:00:59 -08002038bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ALOGV("handlePageFlip");
2041
Brian Andersond6927fb2016-07-23 23:37:30 -07002042 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043
Mathias Agopian4fec8732012-06-29 14:12:52 -07002044 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002045 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002046 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002047
2048 // Store the set of layers that need updates. This set must not change as
2049 // buffers are being latched, as this could result in a deadlock.
2050 // Example: Two producers share the same command stream and:
2051 // 1.) Layer 0 is latched
2052 // 2.) Layer 0 gets a new frame
2053 // 2.) Layer 1 gets a new frame
2054 // 3.) Layer 1 is latched.
2055 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2056 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002057 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002058 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002059 if (layer->hasQueuedFrame()) {
2060 frameQueued = true;
2061 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002063 } else {
2064 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002065 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002066 } else {
2067 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002068 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002069 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002071 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002072 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002073 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002074 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002075 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002076
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002077 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002078
2079 // If we will need to wake up at some time in the future to deal with a
2080 // queued frame that shouldn't be displayed during this vsync period, wake
2081 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002083 signalLayerUpdate();
2084 }
2085
2086 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088}
2089
Mathias Agopianad456f92011-01-13 17:53:01 -08002090void SurfaceFlinger::invalidateHwcGeometry()
2091{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002093}
2094
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002095
Fabien Sanglard830b8472016-11-30 16:35:58 -08002096void SurfaceFlinger::doDisplayComposition(
2097 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002098 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099{
Dan Stoza71433162014-02-04 16:22:36 -08002100 // We only need to actually compose the display if:
2101 // 1) It is being handled by hardware composer, which may need this to
2102 // keep its virtual display state machine in sync, or
2103 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002104 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002105 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002107 return;
2108 }
2109
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 ALOGV("doDisplayComposition");
2111
Mathias Agopian87baae12012-07-31 12:38:26 -07002112 Region dirtyRegion(inDirtyRegion);
2113
Mathias Agopianb8a55602009-06-26 19:06:36 -07002114 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002115 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116
Fabien Sanglard830b8472016-11-30 16:35:58 -08002117 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002118 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002119 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2120 // takes a rectangle, we must make sure to update that whole
2121 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002122 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002123 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002124 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002125 // We need to redraw the rectangle that will be updated
2126 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002127 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002128 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002129 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002130 } else {
2131 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002132 dirtyRegion.set(displayDevice->bounds());
2133 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134 }
2135 }
2136
Fabien Sanglard830b8472016-11-30 16:35:58 -08002137 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002139 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002140 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002141
2142 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002143 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144}
2145
Dan Stoza9e56aa02015-11-02 13:00:03 -08002146bool SurfaceFlinger::doComposeSurfaces(
2147 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002148{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002149 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002150
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002152
2153 mat4 oldColorMatrix;
2154 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2155 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2156 if (applyColorMatrix) {
2157 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2158 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2159 }
2160
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2162 if (hasClientComposition) {
2163 ALOGV("hasClientComposition");
2164
2165 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002166 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002168 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2169 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2170 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2171 }
2172 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002173 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002174
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002175 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2177 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002178 // when using overlays, we assume a fully transparent framebuffer
2179 // NOTE: we could reduce how much we need to clear, for instance
2180 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002181 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002182 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002183 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002184 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002185 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002187
2188 // we remove the scissor part
2189 // we're left with the letterbox region
2190 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002192
2193 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002195
2196 // but limit it to the dirty region
2197 region.andSelf(dirty);
2198
Mathias Agopianb9494d52012-04-18 02:28:45 -07002199 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002200 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002201 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002202 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002203 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002204 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002205
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002207 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002208 // scissor on the main display. It should never be needed
2209 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002210 const Rect& bounds(displayDevice->getBounds());
2211 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002212 if (scissor != bounds) {
2213 // scissor doesn't match the screen's dimensions, so we
2214 // need to clear everything outside of it and enable
2215 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002216
Mathias Agopianf45c5102012-10-24 16:29:17 -07002217 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002218 const uint32_t height = displayDevice->getHeight();
2219 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002220 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002221 }
2222 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002223 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002224
Mathias Agopian85d751c2012-08-29 16:59:24 -07002225 /*
2226 * and then, render the layers targeted at the framebuffer
2227 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002228
Dan Stoza9e56aa02015-11-02 13:00:03 -08002229 ALOGV("Rendering client layers");
2230 const Transform& displayTransform = displayDevice->getTransform();
2231 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002232 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 bool firstLayer = true;
2234 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2235 const Region clip(dirty.intersect(
2236 displayTransform.transform(layer->visibleRegion)));
2237 ALOGV("Layer: %s", layer->getName().string());
2238 ALOGV(" Composition type: %s",
2239 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002240 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002241 switch (layer->getCompositionType(hwcId)) {
2242 case HWC2::Composition::Cursor:
2243 case HWC2::Composition::Device:
2244 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002245 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2247 layer->isOpaque(state) && (state.alpha == 1.0f)
2248 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002249 // never clear the very first layer since we're
2250 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002251 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002253 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002255 case HWC2::Composition::Client: {
2256 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002257 break;
2258 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002260 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002261 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002262 } else {
2263 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002264 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002265 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002266 }
2267 } else {
2268 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002270 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002271 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002272 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002274 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002275 }
2276 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002277
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002278 if (applyColorMatrix) {
2279 getRenderEngine().setupColorTransform(oldColorMatrix);
2280 }
2281
Mathias Agopianf45c5102012-10-24 16:29:17 -07002282 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002283 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002284 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285}
2286
Fabien Sanglard830b8472016-11-30 16:35:58 -08002287void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2288 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002289 RenderEngine& engine(getRenderEngine());
2290 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291}
2292
Dan Stoza7d89d062015-04-30 13:29:25 -07002293status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002294 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002295 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002296 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002297{
Dan Stoza7d89d062015-04-30 13:29:25 -07002298 // add this layer to the current state list
2299 {
2300 Mutex::Autolock _l(mStateLock);
2301 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2302 return NO_MEMORY;
2303 }
2304 mCurrentState.layersSortedByZ.add(lbc);
2305 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2306 }
2307
Mathias Agopian96f08192010-06-02 23:28:45 -07002308 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002309 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002310
Dan Stoza7d89d062015-04-30 13:29:25 -07002311 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002312}
2313
Dan Stoza22851c32016-08-09 13:21:03 -07002314status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002316 sp<Layer> layer = weakLayer.promote();
2317 if (layer == nullptr) {
2318 // The layer has already been removed, carry on
2319 return NO_ERROR;
2320 }
2321
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002322 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2323 if (index >= 0) {
2324 mLayersPendingRemoval.push(layer);
2325 mLayersRemoved = true;
2326 setTransactionFlags(eTransactionNeeded);
2327 return NO_ERROR;
2328 }
2329 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330}
2331
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002332uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002333 return android_atomic_release_load(&mTransactionFlags);
2334}
2335
Mathias Agopian3f844832013-08-07 21:24:32 -07002336uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2338}
2339
Mathias Agopian3f844832013-08-07 21:24:32 -07002340uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2342 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002343 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 }
2345 return old;
2346}
2347
Mathias Agopian8b33f032012-07-24 20:43:54 -07002348void SurfaceFlinger::setTransactionState(
2349 const Vector<ComposerState>& state,
2350 const Vector<DisplayState>& displays,
2351 uint32_t flags)
2352{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002353 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002354 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002355 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002356
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002357 if (flags & eAnimation) {
2358 // For window updates that are part of an animation we must wait for
2359 // previous animation "frames" to be handled.
2360 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002361 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002362 if (CC_UNLIKELY(err != NO_ERROR)) {
2363 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002364 // caller after a few seconds.
2365 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2366 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002367 mAnimTransactionPending = false;
2368 break;
2369 }
2370 }
2371 }
2372
Mathias Agopiane57f2922012-08-09 16:29:12 -07002373 size_t count = displays.size();
2374 for (size_t i=0 ; i<count ; i++) {
2375 const DisplayState& s(displays[i]);
2376 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002377 }
2378
Mathias Agopiane57f2922012-08-09 16:29:12 -07002379 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002380 for (size_t i=0 ; i<count ; i++) {
2381 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002382 // Here we need to check that the interface we're given is indeed
2383 // one of our own. A malicious client could give us a NULL
2384 // IInterface, or one of its own or even one of our own but a
2385 // different type. All these situations would cause us to crash.
2386 //
2387 // NOTE: it would be better to use RTTI as we could directly check
2388 // that we have a Client*. however, RTTI is disabled in Android.
2389 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002390 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002391 if (binder != NULL) {
2392 String16 desc(binder->getInterfaceDescriptor());
2393 if (desc == ISurfaceComposerClient::descriptor) {
2394 sp<Client> client( static_cast<Client *>(s.client.get()) );
2395 transactionFlags |= setClientStateLocked(client, s.state);
2396 }
2397 }
2398 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002399 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002400
Robert Carr2a7dbb42016-05-24 11:41:28 -07002401 // If a synchronous transaction is explicitly requested without any changes,
2402 // force a transaction anyway. This can be used as a flush mechanism for
2403 // previous async transactions.
2404 if (transactionFlags == 0 && (flags & eSynchronous)) {
2405 transactionFlags = eTransactionNeeded;
2406 }
2407
Mathias Agopian386aa982011-11-07 21:58:03 -08002408 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002409 if (mInterceptor.isEnabled()) {
2410 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2411 }
Irvel468051e2016-06-13 16:44:44 -07002412
Mathias Agopian386aa982011-11-07 21:58:03 -08002413 // this triggers the transaction
2414 setTransactionFlags(transactionFlags);
2415
2416 // if this is a synchronous transaction, wait for it to take effect
2417 // before returning.
2418 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002419 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002420 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002421 if (flags & eAnimation) {
2422 mAnimTransactionPending = true;
2423 }
2424 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002425 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2426 if (CC_UNLIKELY(err != NO_ERROR)) {
2427 // just in case something goes wrong in SF, return to the
2428 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002429 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2430 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002431 break;
2432 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002433 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434 }
2435}
2436
Mathias Agopiane57f2922012-08-09 16:29:12 -07002437uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2438{
Jesse Hall9a143922012-10-04 16:29:19 -07002439 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2440 if (dpyIdx < 0)
2441 return 0;
2442
Mathias Agopiane57f2922012-08-09 16:29:12 -07002443 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002444 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002445 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002446 const uint32_t what = s.what;
2447 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002448 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002449 disp.surface = s.surface;
2450 flags |= eDisplayTransactionNeeded;
2451 }
2452 }
2453 if (what & DisplayState::eLayerStackChanged) {
2454 if (disp.layerStack != s.layerStack) {
2455 disp.layerStack = s.layerStack;
2456 flags |= eDisplayTransactionNeeded;
2457 }
2458 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002459 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002460 if (disp.orientation != s.orientation) {
2461 disp.orientation = s.orientation;
2462 flags |= eDisplayTransactionNeeded;
2463 }
2464 if (disp.frame != s.frame) {
2465 disp.frame = s.frame;
2466 flags |= eDisplayTransactionNeeded;
2467 }
2468 if (disp.viewport != s.viewport) {
2469 disp.viewport = s.viewport;
2470 flags |= eDisplayTransactionNeeded;
2471 }
2472 }
Michael Lentine47e45402014-07-18 15:34:25 -07002473 if (what & DisplayState::eDisplaySizeChanged) {
2474 if (disp.width != s.width) {
2475 disp.width = s.width;
2476 flags |= eDisplayTransactionNeeded;
2477 }
2478 if (disp.height != s.height) {
2479 disp.height = s.height;
2480 flags |= eDisplayTransactionNeeded;
2481 }
2482 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002483 }
2484 return flags;
2485}
2486
2487uint32_t SurfaceFlinger::setClientStateLocked(
2488 const sp<Client>& client,
2489 const layer_state_t& s)
2490{
2491 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002492 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002493 if (layer != 0) {
2494 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002495 bool geometryAppliesWithResize =
2496 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002498 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002500 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002501 }
2502 if (what & layer_state_t::eLayerChanged) {
2503 // NOTE: index needs to be calculated before we update the state
2504 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002505 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002506 mCurrentState.layersSortedByZ.removeAt(idx);
2507 mCurrentState.layersSortedByZ.add(layer);
2508 // we need traversal (state changed)
2509 // AND transaction (list changed)
2510 flags |= eTransactionNeeded|eTraversalNeeded;
2511 }
2512 }
2513 if (what & layer_state_t::eSizeChanged) {
2514 if (layer->setSize(s.w, s.h)) {
2515 flags |= eTraversalNeeded;
2516 }
2517 }
2518 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002520 flags |= eTraversalNeeded;
2521 }
2522 if (what & layer_state_t::eMatrixChanged) {
2523 if (layer->setMatrix(s.matrix))
2524 flags |= eTraversalNeeded;
2525 }
2526 if (what & layer_state_t::eTransparentRegionChanged) {
2527 if (layer->setTransparentRegionHint(s.transparentRegion))
2528 flags |= eTraversalNeeded;
2529 }
Dan Stoza23116082015-06-18 14:58:39 -07002530 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002531 if (layer->setFlags(s.flags, s.mask))
2532 flags |= eTraversalNeeded;
2533 }
2534 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002535 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002536 flags |= eTraversalNeeded;
2537 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002538 if (what & layer_state_t::eFinalCropChanged) {
2539 if (layer->setFinalCrop(s.finalCrop))
2540 flags |= eTraversalNeeded;
2541 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002542 if (what & layer_state_t::eLayerStackChanged) {
2543 // NOTE: index needs to be calculated before we update the state
2544 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002545 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002546 mCurrentState.layersSortedByZ.removeAt(idx);
2547 mCurrentState.layersSortedByZ.add(layer);
2548 // we need traversal (state changed)
2549 // AND transaction (list changed)
2550 flags |= eTransactionNeeded|eTraversalNeeded;
2551 }
2552 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002553 if (what & layer_state_t::eDeferTransaction) {
2554 layer->deferTransactionUntil(s.handle, s.frameNumber);
2555 // We don't trigger a traversal here because if no other state is
2556 // changed, we don't want this to cause any more work
2557 }
Robert Carrc3574f72016-03-24 12:19:32 -07002558 if (what & layer_state_t::eOverrideScalingModeChanged) {
2559 layer->setOverrideScalingMode(s.overrideScalingMode);
2560 // We don't trigger a traversal here because if no other state is
2561 // changed, we don't want this to cause any more work
2562 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002563 }
2564 return flags;
2565}
2566
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002567status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002568 const String8& name,
2569 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002570 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2571 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002573 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002574 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002575 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002576 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002577 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002578
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002579 status_t result = NO_ERROR;
2580
2581 sp<Layer> layer;
2582
Mathias Agopian3165cc22012-08-08 19:42:09 -07002583 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2584 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002585 result = createNormalLayer(client,
2586 name, w, h, flags, format,
2587 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002589 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002590 result = createDimLayer(client,
2591 name, w, h, flags,
2592 handle, gbp, &layer);
2593 break;
2594 default:
2595 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002596 break;
2597 }
2598
Dan Stoza7d89d062015-04-30 13:29:25 -07002599 if (result != NO_ERROR) {
2600 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002601 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002602
2603 result = addClientLayer(client, *handle, *gbp, layer);
2604 if (result != NO_ERROR) {
2605 return result;
2606 }
Irvelffc9efc2016-07-27 15:16:37 -07002607 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002608
2609 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002610 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002611}
2612
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002613status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2614 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2615 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616{
2617 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002618 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 case PIXEL_FORMAT_TRANSPARENT:
2620 case PIXEL_FORMAT_TRANSLUCENT:
2621 format = PIXEL_FORMAT_RGBA_8888;
2622 break;
2623 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002624 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625 break;
2626 }
2627
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002628 *outLayer = new Layer(this, client, name, w, h, flags);
2629 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2630 if (err == NO_ERROR) {
2631 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002632 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002634
2635 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2636 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637}
2638
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002639status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2640 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2641 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002643 *outLayer = new LayerDim(this, client, name, w, h, flags);
2644 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002645 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002646 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002647}
2648
Mathias Agopianac9fa422013-02-11 16:40:36 -08002649status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650{
Mathias Agopian67106042013-03-14 19:18:13 -07002651 // called by the window manager when it wants to remove a Layer
2652 status_t err = NO_ERROR;
2653 sp<Layer> l(client->getLayerUser(handle));
2654 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002655 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002656 err = removeLayer(l);
2657 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2658 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002659 }
2660 return err;
2661}
2662
Mathias Agopian13127d82013-03-05 17:47:11 -08002663status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002664{
Mathias Agopian67106042013-03-14 19:18:13 -07002665 // called by ~LayerCleaner() when all references to the IBinder (handle)
2666 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002667 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668}
2669
Mathias Agopianb60314a2012-04-10 22:09:54 -07002670// ---------------------------------------------------------------------------
2671
Andy McFadden13a082e2012-08-24 10:16:42 -07002672void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002673 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002674 Vector<ComposerState> state;
2675 Vector<DisplayState> displays;
2676 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002677 d.what = DisplayState::eDisplayProjectionChanged |
2678 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002679 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002680 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002681 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002682 d.frame.makeInvalid();
2683 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002684 d.width = 0;
2685 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002686 displays.add(d);
2687 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002688 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002689
Dan Stoza9e56aa02015-11-02 13:00:03 -08002690 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2691 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002692 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002693}
2694
2695void SurfaceFlinger::initializeDisplays() {
2696 class MessageScreenInitialized : public MessageBase {
2697 SurfaceFlinger* flinger;
2698 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002699 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002700 virtual bool handler() {
2701 flinger->onInitializeDisplays();
2702 return true;
2703 }
2704 };
2705 sp<MessageBase> msg = new MessageScreenInitialized(this);
2706 postMessageAsync(msg); // we may be called from main thread, use async message
2707}
2708
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002709void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2710 int mode) {
2711 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2712 this);
2713 int32_t type = hw->getDisplayType();
2714 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002715
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002716 if (mode == currentMode) {
2717 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002718 return;
2719 }
2720
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002721 hw->setPowerMode(mode);
2722 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2723 ALOGW("Trying to set power mode for virtual display");
2724 return;
2725 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002726
Irvelffc9efc2016-07-27 15:16:37 -07002727 if (mInterceptor.isEnabled()) {
2728 Mutex::Autolock _l(mStateLock);
2729 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2730 if (idx < 0) {
2731 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2732 return;
2733 }
2734 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2735 }
2736
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002737 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002738 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002739 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002740 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2741 // FIXME: eventthread only knows about the main display right now
2742 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002743 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002746 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002747 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002748 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002749
2750 struct sched_param param = {0};
2751 param.sched_priority = 1;
2752 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2753 ALOGW("Couldn't set SCHED_FIFO on display on");
2754 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002755 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002756 // Turn off the display
2757 struct sched_param param = {0};
2758 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2759 ALOGW("Couldn't set SCHED_OTHER on display off");
2760 }
2761
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002762 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002763 disableHardwareVsync(true); // also cancels any in-progress resync
2764
Mathias Agopiancde87a32012-09-13 14:09:01 -07002765 // FIXME: eventthread only knows about the main display right now
2766 mEventThread->onScreenReleased();
2767 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002768
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002769 getHwComposer().setPowerMode(type, mode);
2770 mVisibleRegionsDirty = true;
2771 // from this point on, SF will stop drawing on this display
2772 } else {
2773 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002774 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002775}
2776
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002777void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2778 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002779 SurfaceFlinger& mFlinger;
2780 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002781 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002782 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002783 MessageSetPowerMode(SurfaceFlinger& flinger,
2784 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2785 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002786 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002787 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002788 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002789 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002790 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002791 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002792 ALOGW("Attempt to set power mode = %d for virtual display",
2793 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002794 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002795 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002796 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002797 return true;
2798 }
2799 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002800 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002801 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002802}
2803
2804// ---------------------------------------------------------------------------
2805
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2807{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002809
Mathias Agopianbd115332013-04-18 16:41:04 -07002810 IPCThreadState* ipc = IPCThreadState::self();
2811 const int pid = ipc->getCallingPid();
2812 const int uid = ipc->getCallingUid();
2813 if ((uid != AID_SHELL) &&
2814 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002815 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002816 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002818 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002819 // (this would indicate SF is stuck, but we want to be able to
2820 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002821 status_t err = mStateLock.timedLock(s2ns(1));
2822 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002823 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002824 result.appendFormat(
2825 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2826 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002827 }
2828
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002829 bool dumpAll = true;
2830 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002831 size_t numArgs = args.size();
2832 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002833 if ((index < numArgs) &&
2834 (args[index] == String16("--list"))) {
2835 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002836 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002837 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002838 }
2839
2840 if ((index < numArgs) &&
2841 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002842 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002843 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002844 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002845 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002846
2847 if ((index < numArgs) &&
2848 (args[index] == String16("--latency-clear"))) {
2849 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002850 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002851 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002852 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002853
2854 if ((index < numArgs) &&
2855 (args[index] == String16("--dispsync"))) {
2856 index++;
2857 mPrimaryDispSync.dump(result);
2858 dumpAll = false;
2859 }
Dan Stozab90cf072015-03-05 11:05:59 -08002860
2861 if ((index < numArgs) &&
2862 (args[index] == String16("--static-screen"))) {
2863 index++;
2864 dumpStaticScreenStats(result);
2865 dumpAll = false;
2866 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002867
2868 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002869 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002870 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002871 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002872 dumpAll = false;
2873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002875
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002876 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002877 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002878 }
2879
Mathias Agopian9795c422009-08-26 16:36:26 -07002880 if (locked) {
2881 mStateLock.unlock();
2882 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 }
2884 write(fd, result.string(), result.size());
2885 return NO_ERROR;
2886}
2887
Dan Stozac7014012014-02-14 15:03:43 -08002888void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2889 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002890{
2891 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2892 const size_t count = currentLayers.size();
2893 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002894 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002895 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002896 }
2897}
2898
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002899void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002900 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002901{
2902 String8 name;
2903 if (index < args.size()) {
2904 name = String8(args[index]);
2905 index++;
2906 }
2907
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2909 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002910 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002911
2912 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002913 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002914 } else {
2915 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2916 const size_t count = currentLayers.size();
2917 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002918 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002919 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002920 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002921 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002922 }
2923 }
2924}
2925
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002926void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002927 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002928{
2929 String8 name;
2930 if (index < args.size()) {
2931 name = String8(args[index]);
2932 index++;
2933 }
2934
2935 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2936 const size_t count = currentLayers.size();
2937 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002938 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002939 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002940 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002941 }
2942 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002943
Svetoslavd85084b2014-03-20 10:28:31 -07002944 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002945}
2946
Jamie Gennis6547ff42013-07-16 20:12:42 -07002947// This should only be called from the main thread. Otherwise it would need
2948// the lock and should use mCurrentState rather than mDrawingState.
2949void SurfaceFlinger::logFrameStats() {
2950 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2951 const size_t count = drawingLayers.size();
2952 for (size_t i=0 ; i<count ; i++) {
2953 const sp<Layer>& layer(drawingLayers[i]);
2954 layer->logFrameStats();
2955 }
2956
2957 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2958}
2959
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002960void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07002961{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002962 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07002963#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002964 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07002965#endif
2966#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002967 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07002968#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002969 if (isLayerTripleBufferingDisabled())
2970 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002971 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07002972}
2973
Dan Stozab90cf072015-03-05 11:05:59 -08002974void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2975{
2976 result.appendFormat("Static screen stats:\n");
2977 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2978 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2979 float percent = 100.0f *
2980 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2981 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2982 b + 1, bucketTimeSec, percent);
2983 }
2984 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2985 float percent = 100.0f *
2986 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2987 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2988 NUM_BUCKETS - 1, bucketTimeSec, percent);
2989}
2990
Dan Stozae77c7662016-05-13 11:37:28 -07002991void SurfaceFlinger::recordBufferingStats(const char* layerName,
2992 std::vector<OccupancyTracker::Segment>&& history) {
2993 Mutex::Autolock lock(mBufferingStatsMutex);
2994 auto& stats = mBufferingStats[layerName];
2995 for (const auto& segment : history) {
2996 if (!segment.usedThirdBuffer) {
2997 stats.twoBufferTime += segment.totalTime;
2998 }
2999 if (segment.occupancyAverage < 1.0f) {
3000 stats.doubleBufferedTime += segment.totalTime;
3001 } else if (segment.occupancyAverage < 2.0f) {
3002 stats.tripleBufferedTime += segment.totalTime;
3003 }
3004 ++stats.numSegments;
3005 stats.totalTime += segment.totalTime;
3006 }
3007}
3008
Brian Andersond6927fb2016-07-23 23:37:30 -07003009void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3010 result.appendFormat("Layer frame timestamps:\n");
3011
3012 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3013 const size_t count = currentLayers.size();
3014 for (size_t i=0 ; i<count ; i++) {
3015 currentLayers[i]->dumpFrameEvents(result);
3016 }
3017}
3018
Dan Stozae77c7662016-05-13 11:37:28 -07003019void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3020 result.append("Buffering stats:\n");
3021 result.append(" [Layer name] <Active time> <Two buffer> "
3022 "<Double buffered> <Triple buffered>\n");
3023 Mutex::Autolock lock(mBufferingStatsMutex);
3024 typedef std::tuple<std::string, float, float, float> BufferTuple;
3025 std::map<float, BufferTuple, std::greater<float>> sorted;
3026 for (const auto& statsPair : mBufferingStats) {
3027 const char* name = statsPair.first.c_str();
3028 const BufferingStats& stats = statsPair.second;
3029 if (stats.numSegments == 0) {
3030 continue;
3031 }
3032 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3033 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3034 stats.totalTime;
3035 float doubleBufferRatio = static_cast<float>(
3036 stats.doubleBufferedTime) / stats.totalTime;
3037 float tripleBufferRatio = static_cast<float>(
3038 stats.tripleBufferedTime) / stats.totalTime;
3039 sorted.insert({activeTime, {name, twoBufferRatio,
3040 doubleBufferRatio, tripleBufferRatio}});
3041 }
3042 for (const auto& sortedPair : sorted) {
3043 float activeTime = sortedPair.first;
3044 const BufferTuple& values = sortedPair.second;
3045 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3046 std::get<0>(values).c_str(), activeTime,
3047 std::get<1>(values), std::get<2>(values),
3048 std::get<3>(values));
3049 }
3050 result.append("\n");
3051}
3052
3053
Mathias Agopian74d211a2013-04-22 16:55:35 +02003054void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3055 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003056{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003057 bool colorize = false;
3058 if (index < args.size()
3059 && (args[index] == String16("--color"))) {
3060 colorize = true;
3061 index++;
3062 }
3063
3064 Colorizer colorizer(colorize);
3065
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003066 // figure out if we're stuck somewhere
3067 const nsecs_t now = systemTime();
3068 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3069 const nsecs_t inTransaction(mDebugInTransaction);
3070 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3071 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3072
3073 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003074 * Dump library configuration.
3075 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003076
3077 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003078 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003079 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003080 appendSfConfigString(result);
3081 appendUiConfigString(result);
3082 appendGuiConfigString(result);
3083 result.append("\n");
3084
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003085 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003086 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003087 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003088 result.append(SyncFeatures::getInstance().toString());
3089 result.append("\n");
3090
Dan Stoza9e56aa02015-11-02 13:00:03 -08003091 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3092
Andy McFadden41d67d72014-04-25 16:58:34 -07003093 colorizer.bold(result);
3094 result.append("DispSync configuration: ");
3095 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003096 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3097 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003098 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3099 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003100 result.append("\n");
3101
Dan Stozab90cf072015-03-05 11:05:59 -08003102 // Dump static screen stats
3103 result.append("\n");
3104 dumpStaticScreenStats(result);
3105 result.append("\n");
3106
Dan Stozae77c7662016-05-13 11:37:28 -07003107 dumpBufferingStats(result);
3108
Andy McFadden4803b742012-09-24 19:07:20 -07003109 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003110 * Dump the visible layer list
3111 */
3112 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3113 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003114 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003115 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003116 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003117 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003118 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003119 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003120 }
3121
3122 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003123 * Dump Display state
3124 */
3125
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003126 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003127 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003128 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003129 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3130 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003131 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003132 }
3133
3134 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135 * Dump SurfaceFlinger global state
3136 */
3137
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003138 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003139 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003140 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003141
Mathias Agopian888c8222012-08-04 21:10:38 -07003142 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003143 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003144
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003145 colorizer.bold(result);
3146 result.appendFormat("EGL implementation : %s\n",
3147 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3148 colorizer.reset(result);
3149 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003150 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003151
Mathias Agopian875d8e12013-06-07 15:35:48 -07003152 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003153
Mathias Agopian42977342012-08-05 00:40:46 -07003154 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003155 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3156 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003157 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003158 " last eglSwapBuffers() time: %f us\n"
3159 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003160 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003161 " refresh-rate : %f fps\n"
3162 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003163 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003164 " gpu_to_cpu_unsupported : %d\n"
3165 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003166 mLastSwapBufferTime/1000.0,
3167 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003168 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003169 1e9 / activeConfig->getVsyncPeriod(),
3170 activeConfig->getDpiX(),
3171 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003172 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003173
Mathias Agopian74d211a2013-04-22 16:55:35 +02003174 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003175 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003176
Mathias Agopian74d211a2013-04-22 16:55:35 +02003177 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003178 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003179
3180 /*
3181 * VSYNC state
3182 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003183 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003184 result.append("\n");
3185
3186 /*
3187 * HWC layer minidump
3188 */
3189 for (size_t d = 0; d < mDisplays.size(); d++) {
3190 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3191 int32_t hwcId = displayDevice->getHwcDisplayId();
3192 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3193 continue;
3194 }
3195
3196 result.appendFormat("Display %d HWC layers:\n", hwcId);
3197 Layer::miniDumpHeader(result);
3198 for (size_t l = 0; l < count; l++) {
3199 const sp<Layer>& layer(currentLayers[l]);
3200 layer->miniDump(result, hwcId);
3201 }
3202 result.append("\n");
3203 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003204
3205 /*
3206 * Dump HWComposer state
3207 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003208 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003209 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003210 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003211 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003212 result.appendFormat(" h/w composer %s\n",
3213 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003214 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003215
3216 /*
3217 * Dump gralloc state
3218 */
3219 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3220 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003221}
3222
Mathias Agopian13127d82013-03-05 17:47:11 -08003223const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003224SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003225 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003226 wp<IBinder> dpy;
3227 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3228 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3229 dpy = mDisplays.keyAt(i);
3230 break;
3231 }
3232 }
3233 if (dpy == NULL) {
3234 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3235 // Just use the primary display so we have something to return
3236 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3237 }
3238 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003239}
3240
Keun young Park63f165f2012-08-31 10:53:36 -07003241bool SurfaceFlinger::startDdmConnection()
3242{
3243 void* libddmconnection_dso =
3244 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3245 if (!libddmconnection_dso) {
3246 return false;
3247 }
3248 void (*DdmConnection_start)(const char* name);
3249 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003250 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003251 if (!DdmConnection_start) {
3252 dlclose(libddmconnection_dso);
3253 return false;
3254 }
3255 (*DdmConnection_start)(getServiceName());
3256 return true;
3257}
3258
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003259status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260 switch (code) {
3261 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003262 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003263 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003265 case CLEAR_ANIMATION_FRAME_STATS:
3266 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003267 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003268 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 {
3270 // codes that require permission check
3271 IPCThreadState* ipc = IPCThreadState::self();
3272 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003273 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003274 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003275 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003276 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003277 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003279 break;
3280 }
3281 case CAPTURE_SCREEN:
3282 {
3283 // codes that require permission check
3284 IPCThreadState* ipc = IPCThreadState::self();
3285 const int pid = ipc->getCallingPid();
3286 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003287 if ((uid != AID_GRAPHICS) &&
3288 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003289 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003290 return PERMISSION_DENIED;
3291 }
3292 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293 }
3294 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003295 return OK;
3296}
3297
3298status_t SurfaceFlinger::onTransact(
3299 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3300{
3301 status_t credentialCheck = CheckTransactCodeCredentials(code);
3302 if (credentialCheck != OK) {
3303 return credentialCheck;
3304 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003305
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003306 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3307 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003308 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003309 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003310 IPCThreadState* ipc = IPCThreadState::self();
3311 const int pid = ipc->getCallingPid();
3312 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003313 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003314 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 return PERMISSION_DENIED;
3316 }
3317 int n;
3318 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003319 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003320 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 return NO_ERROR;
3322 case 1002: // SHOW_UPDATES
3323 n = data.readInt32();
3324 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003325 invalidateHwcGeometry();
3326 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003327 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003329 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003330 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003332 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003333 setTransactionFlags(
3334 eTransactionNeeded|
3335 eDisplayTransactionNeeded|
3336 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003337 return NO_ERROR;
3338 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003339 case 1006:{ // send empty update
3340 signalRefresh();
3341 return NO_ERROR;
3342 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003343 case 1008: // toggle use of hw composer
3344 n = data.readInt32();
3345 mDebugDisableHWC = n ? 1 : 0;
3346 invalidateHwcGeometry();
3347 repaintEverything();
3348 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003349 case 1009: // toggle use of transform hint
3350 n = data.readInt32();
3351 mDebugDisableTransformHint = n ? 1 : 0;
3352 invalidateHwcGeometry();
3353 repaintEverything();
3354 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003356 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003357 reply->writeInt32(0);
3358 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003359 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003360 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361 return NO_ERROR;
3362 case 1013: {
3363 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003364 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3365 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003366 return NO_ERROR;
3367 }
3368 case 1014: {
3369 // daltonize
3370 n = data.readInt32();
3371 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003372 case 1:
3373 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3374 break;
3375 case 2:
3376 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3377 break;
3378 case 3:
3379 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3380 break;
3381 default:
3382 mDaltonizer.setType(ColorBlindnessType::None);
3383 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003384 }
3385 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003386 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003387 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003388 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003389 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003390 invalidateHwcGeometry();
3391 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003392 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003394 case 1015: {
3395 // apply a color matrix
3396 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003397 if (n) {
3398 // color matrix is sent as mat3 matrix followed by vec3
3399 // offset, then packed into a mat4 where the last row is
3400 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003401 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003402 for (size_t j = 0; j < 4; j++) {
3403 mColorMatrix[i][j] = data.readFloat();
3404 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003405 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003406 } else {
3407 mColorMatrix = mat4();
3408 }
3409 invalidateHwcGeometry();
3410 repaintEverything();
3411 return NO_ERROR;
3412 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003413 // This is an experimental interface
3414 // Needs to be shifted to proper binder interface when we productize
3415 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003416 n = data.readInt32();
3417 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003418 return NO_ERROR;
3419 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003420 case 1017: {
3421 n = data.readInt32();
3422 mForceFullDamage = static_cast<bool>(n);
3423 return NO_ERROR;
3424 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003425 case 1018: { // Modify Choreographer's phase offset
3426 n = data.readInt32();
3427 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3428 return NO_ERROR;
3429 }
3430 case 1019: { // Modify SurfaceFlinger's phase offset
3431 n = data.readInt32();
3432 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3433 return NO_ERROR;
3434 }
Irvel468051e2016-06-13 16:44:44 -07003435 case 1020: { // Layer updates interceptor
3436 n = data.readInt32();
3437 if (n) {
3438 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003439 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003440 }
3441 else{
3442 ALOGV("Interceptor disabled");
3443 mInterceptor.disable();
3444 }
3445 return NO_ERROR;
3446 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003447 case 1021: { // Disable HWC virtual displays
3448 n = data.readInt32();
3449 mUseHwcVirtualDisplays = !n;
3450 return NO_ERROR;
3451 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003452 }
3453 }
3454 return err;
3455}
3456
Mathias Agopian53331da2011-08-22 21:44:41 -07003457void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003458 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003459 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003460}
3461
Mathias Agopian59119e62010-10-11 12:37:43 -07003462// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003463// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003464// ---------------------------------------------------------------------------
3465
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003466/* The code below is here to handle b/8734824
3467 *
3468 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003469 * from the surfaceflinger thread to the calling binder thread, where they
3470 * are executed. This allows the calling thread in the calling process to be
3471 * reused and not depend on having "enough" binder threads to handle the
3472 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003473 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003474class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003475 /* Parts of GraphicProducerWrapper are run on two different threads,
3476 * communicating by sending messages via Looper but also by shared member
3477 * data. Coherence maintenance is subtle and in places implicit (ugh).
3478 *
3479 * Don't rely on Looper's sendMessage/handleMessage providing
3480 * release/acquire semantics for any data not actually in the Message.
3481 * Data going from surfaceflinger to binder threads needs to be
3482 * synchronized explicitly.
3483 *
3484 * Barrier open/wait do provide release/acquire semantics. This provides
3485 * implicit synchronization for data coming back from binder to
3486 * surfaceflinger threads.
3487 */
3488
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003489 sp<IGraphicBufferProducer> impl;
3490 sp<Looper> looper;
3491 status_t result;
3492 bool exitPending;
3493 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003494 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003495 uint32_t code;
3496 Parcel const* data;
3497 Parcel* reply;
3498
3499 enum {
3500 MSG_API_CALL,
3501 MSG_EXIT
3502 };
3503
3504 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003505 * Called on surfaceflinger thread. This is called by our "fake"
3506 * BpGraphicBufferProducer. We package the data and reply Parcel and
3507 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003508 */
3509 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003510 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003511 this->code = code;
3512 this->data = &data;
3513 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003514 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003515 // if we've exited, we run the message synchronously right here.
3516 // note (JH): as far as I can tell from looking at the code, this
3517 // never actually happens. if it does, i'm not sure if it happens
3518 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003519 handleMessage(Message(MSG_API_CALL));
3520 } else {
3521 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003522 // Prevent stores to this->{code, data, reply} from being
3523 // reordered later than the construction of Message.
3524 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003525 looper->sendMessage(this, Message(MSG_API_CALL));
3526 barrier.wait();
3527 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003528 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003529 }
3530
3531 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003532 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533 * call the real BpGraphicBufferProducer.
3534 */
3535 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003536 int what = message.what;
3537 // Prevent reads below from happening before the read from Message
3538 atomic_thread_fence(memory_order_acquire);
3539 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003540 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003541 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003542 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003543 exitRequested = true;
3544 }
3545 }
3546
3547public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003548 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003549 : impl(impl),
3550 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003551 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003552 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003553 exitRequested(false),
3554 code(0),
3555 data(NULL),
3556 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003557 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003558
Jesse Hallb154c422014-07-13 12:47:02 -07003559 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003560 status_t waitForResponse() {
3561 do {
3562 looper->pollOnce(-1);
3563 } while (!exitRequested);
3564 return result;
3565 }
3566
Jesse Hallb154c422014-07-13 12:47:02 -07003567 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003568 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003569 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003570 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003571 // Ensure this->result is visible to the binder thread before it
3572 // handles the message.
3573 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003574 looper->sendMessage(this, Message(MSG_EXIT));
3575 }
3576};
3577
3578
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003579status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3580 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003581 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003582 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003583 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003584
3585 if (CC_UNLIKELY(display == 0))
3586 return BAD_VALUE;
3587
3588 if (CC_UNLIKELY(producer == 0))
3589 return BAD_VALUE;
3590
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003591 // if we have secure windows on this display, never allow the screen capture
3592 // unless the producer interface is local (i.e.: we can take a screenshot for
3593 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003594 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003595
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003596 // Convert to surfaceflinger's internal rotation type.
3597 Transform::orientation_flags rotationFlags;
3598 switch (rotation) {
3599 case ISurfaceComposer::eRotateNone:
3600 rotationFlags = Transform::ROT_0;
3601 break;
3602 case ISurfaceComposer::eRotate90:
3603 rotationFlags = Transform::ROT_90;
3604 break;
3605 case ISurfaceComposer::eRotate180:
3606 rotationFlags = Transform::ROT_180;
3607 break;
3608 case ISurfaceComposer::eRotate270:
3609 rotationFlags = Transform::ROT_270;
3610 break;
3611 default:
3612 rotationFlags = Transform::ROT_0;
3613 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3614 break;
3615 }
3616
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003617 class MessageCaptureScreen : public MessageBase {
3618 SurfaceFlinger* flinger;
3619 sp<IBinder> display;
3620 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003621 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003622 uint32_t reqWidth, reqHeight;
3623 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003624 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003625 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003626 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003627 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003628 public:
3629 MessageCaptureScreen(SurfaceFlinger* flinger,
3630 const sp<IBinder>& display,
3631 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003632 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003633 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003634 bool useIdentityTransform,
3635 Transform::orientation_flags rotation,
3636 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003637 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003638 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003639 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003640 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003641 rotation(rotation), result(PERMISSION_DENIED),
3642 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003643 {
3644 }
3645 status_t getResult() const {
3646 return result;
3647 }
3648 virtual bool handler() {
3649 Mutex::Autolock _l(flinger->mStateLock);
3650 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003651 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003652 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003653 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003654 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003655 return true;
3656 }
3657 };
3658
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003659 // this creates a "fake" BBinder which will serve as a "fake" remote
3660 // binder to receive the marshaled calls and forward them to the
3661 // real remote (a BpGraphicBufferProducer)
3662 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3663
3664 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3665 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003666 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003667 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003668 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003669 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003670
3671 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003672 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003673 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003674 }
3675 return res;
3676}
3677
Mathias Agopian180f10d2013-04-10 22:55:41 -07003678
3679void SurfaceFlinger::renderScreenImplLocked(
3680 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003681 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003682 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003683 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003684{
3685 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003686 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003687
3688 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003689 const int32_t hw_w = hw->getWidth();
3690 const int32_t hw_h = hw->getHeight();
3691 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003692 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003693
Dan Stozac1879002014-05-22 15:59:05 -07003694 // if a default or invalid sourceCrop is passed in, set reasonable values
3695 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3696 !sourceCrop.isValid()) {
3697 sourceCrop.setLeftTop(Point(0, 0));
3698 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3699 }
3700
3701 // ensure that sourceCrop is inside screen
3702 if (sourceCrop.left < 0) {
3703 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3704 }
Dan Stozabe31f442014-06-11 11:20:54 -07003705 if (sourceCrop.right > hw_w) {
3706 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003707 }
3708 if (sourceCrop.top < 0) {
3709 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3710 }
Dan Stozabe31f442014-06-11 11:20:54 -07003711 if (sourceCrop.bottom > hw_h) {
3712 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003713 }
3714
Mathias Agopian180f10d2013-04-10 22:55:41 -07003715 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003716 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003717
3718 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003719 engine.setViewportAndProjection(
3720 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003721 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003722
3723 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003724 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003725
3726 const LayerVector& layers( mDrawingState.layersSortedByZ );
3727 const size_t count = layers.size();
3728 for (size_t i=0 ; i<count ; ++i) {
3729 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003730 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003731 if (state.layerStack == hw->getLayerStack()) {
3732 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3733 if (layer->isVisible()) {
3734 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003735 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003736 if (filtering) layer->setFiltering(false);
3737 }
3738 }
3739 }
3740 }
3741
Mathias Agopian931bda12013-08-28 18:11:46 -07003742 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003743}
3744
3745
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003746status_t SurfaceFlinger::captureScreenImplLocked(
3747 const sp<const DisplayDevice>& hw,
3748 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003749 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003750 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003751 bool useIdentityTransform, Transform::orientation_flags rotation,
3752 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003753{
3754 ATRACE_CALL();
3755
Mathias Agopian180f10d2013-04-10 22:55:41 -07003756 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003757 uint32_t hw_w = hw->getWidth();
3758 uint32_t hw_h = hw->getHeight();
3759
3760 if (rotation & Transform::ROT_90) {
3761 std::swap(hw_w, hw_h);
3762 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003763
Mathias Agopian180f10d2013-04-10 22:55:41 -07003764 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3765 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3766 reqWidth, reqHeight, hw_w, hw_h);
3767 return BAD_VALUE;
3768 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003769
Mathias Agopian180f10d2013-04-10 22:55:41 -07003770 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3771 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3772
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003773 bool secureLayerIsVisible = false;
3774 const LayerVector& layers(mDrawingState.layersSortedByZ);
3775 const size_t count = layers.size();
3776 for (size_t i = 0 ; i < count ; ++i) {
3777 const sp<Layer>& layer(layers[i]);
3778 const Layer::State& state(layer->getDrawingState());
3779 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3780 state.z <= maxLayerZ && layer->isVisible() &&
3781 layer->isSecure()) {
3782 secureLayerIsVisible = true;
3783 }
3784 }
3785
3786 if (!isLocalScreenshot && secureLayerIsVisible) {
3787 ALOGW("FB is protected: PERMISSION_DENIED");
3788 return PERMISSION_DENIED;
3789 }
3790
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003791 // create a surface (because we're a producer, and we need to
3792 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003793 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003794
3795 // Put the screenshot Surface into async mode so that
3796 // Layer::headFenceHasSignaled will always return true and we'll latch the
3797 // first buffer regardless of whether or not its acquire fence has
3798 // signaled. This is needed to avoid a race condition in the rotation
3799 // animation. See b/30209608
3800 sur->setAsyncMode(true);
3801
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003802 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003803
Michael Lentine5a16a622015-05-21 13:48:24 -07003804 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3805 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003806 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3807 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003808
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003809 int err = 0;
3810 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003811 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003812 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3813 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003814
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003815 if (err == NO_ERROR) {
3816 ANativeWindowBuffer* buffer;
3817 /* TODO: Once we have the sync framework everywhere this can use
3818 * server-side waits on the fence that dequeueBuffer returns.
3819 */
3820 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3821 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003822 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003823 // create an EGLImage from the buffer so we can later
3824 // turn it into a texture
3825 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3826 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3827 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003828 // this binds the given EGLImage as a framebuffer for the
3829 // duration of this scope.
3830 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3831 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003832 // this will in fact render into our dequeued buffer
3833 // via an FBO, which means we didn't have to create
3834 // an EGLSurface and therefore we're not
3835 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003836 renderScreenImplLocked(
3837 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3838 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003839
Riley Andrews86639902014-08-15 12:27:24 -07003840 // Attempt to create a sync khr object that can produce a sync point. If that
3841 // isn't available, create a non-dupable sync object in the fallback path and
3842 // wait on it directly.
3843 EGLSyncKHR sync;
3844 if (!DEBUG_SCREENSHOTS) {
3845 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003846 // native fence fd will not be populated until flush() is done.
3847 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003848 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003849 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003850 }
Riley Andrews86639902014-08-15 12:27:24 -07003851 if (sync != EGL_NO_SYNC_KHR) {
3852 // get the sync fd
3853 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3854 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3855 ALOGW("captureScreen: failed to dup sync khr object");
3856 syncFd = -1;
3857 }
3858 eglDestroySyncKHR(mEGLDisplay, sync);
3859 } else {
3860 // fallback path
3861 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3862 if (sync != EGL_NO_SYNC_KHR) {
3863 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3864 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3865 EGLint eglErr = eglGetError();
3866 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3867 ALOGW("captureScreen: fence wait timed out");
3868 } else {
3869 ALOGW_IF(eglErr != EGL_SUCCESS,
3870 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3871 }
3872 eglDestroySyncKHR(mEGLDisplay, sync);
3873 } else {
3874 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3875 }
3876 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003877 if (DEBUG_SCREENSHOTS) {
3878 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3879 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3880 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3881 hw, minLayerZ, maxLayerZ);
3882 delete [] pixels;
3883 }
3884
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003885 } else {
3886 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3887 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003888 window->cancelBuffer(window, buffer, syncFd);
3889 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003890 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003891 // destroy our image
3892 eglDestroyImageKHR(mEGLDisplay, image);
3893 } else {
3894 result = BAD_VALUE;
3895 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003896 if (buffer) {
3897 // queueBuffer takes ownership of syncFd
3898 result = window->queueBuffer(window, buffer, syncFd);
3899 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003900 }
3901 } else {
3902 result = BAD_VALUE;
3903 }
3904 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3905 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003906
Mathias Agopian74c40c02010-09-29 13:02:36 -07003907 return result;
3908}
3909
Mathias Agopiand5556842013-09-19 17:08:37 -07003910void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3911 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003912 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003913 for (size_t y=0 ; y<h ; y++) {
3914 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3915 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003916 if (p[x] != 0xFF000000) return;
3917 }
3918 }
3919 ALOGE("*** we just took a black screenshot ***\n"
3920 "requested minz=%d, maxz=%d, layerStack=%d",
3921 minLayerZ, maxLayerZ, hw->getLayerStack());
3922 const LayerVector& layers( mDrawingState.layersSortedByZ );
3923 const size_t count = layers.size();
3924 for (size_t i=0 ; i<count ; ++i) {
3925 const sp<Layer>& layer(layers[i]);
3926 const Layer::State& state(layer->getDrawingState());
3927 const bool visible = (state.layerStack == hw->getLayerStack())
3928 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3929 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003930 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003931 visible ? '+' : '-',
3932 i, layer->getName().string(), state.layerStack, state.z,
3933 layer->isVisible(), state.flags, state.alpha);
3934 }
3935 }
3936}
3937
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003938// ---------------------------------------------------------------------------
3939
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003940SurfaceFlinger::LayerVector::LayerVector() {
3941}
3942
3943SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003944 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003945}
3946
3947int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3948 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003949{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003950 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003951 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3952 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003953
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003954 uint32_t ls = l->getCurrentState().layerStack;
3955 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003956 if (ls != rs)
3957 return ls - rs;
3958
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003959 uint32_t lz = l->getCurrentState().z;
3960 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003961 if (lz != rz)
3962 return lz - rz;
3963
3964 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003965}
3966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003967}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003968
3969
3970#if defined(__gl_h_)
3971#error "don't include gl/gl.h in this file"
3972#endif
3973
3974#if defined(__gl2_h_)
3975#error "don't include gl2/gl2.h in this file"
3976#endif