blob: 8b10344b58805a981e3d4e52c42af28263527dca [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
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,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700578 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700579 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700580 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700581 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700582 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700583 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700584 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700585 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700586 };
587 return NO_ERROR;
588}
589
Dan Stoza7f7da322014-05-02 15:26:25 -0700590status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
591 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700592 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700593 return BAD_VALUE;
594 }
595
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500596 if (!display.get())
597 return NAME_NOT_FOUND;
598
Jesse Hall692c7232012-11-08 15:41:56 -0800599 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700600 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800601 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700602 type = i;
603 break;
604 }
605 }
606
607 if (type < 0) {
608 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700609 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700610
Mathias Agopian8b736f12012-08-13 17:54:26 -0700611 // TODO: Not sure if display density should handled by SF any longer
612 class Density {
613 static int getDensityFromProperty(char const* propName) {
614 char property[PROPERTY_VALUE_MAX];
615 int density = 0;
616 if (property_get(propName, property, NULL) > 0) {
617 density = atoi(property);
618 }
619 return density;
620 }
621 public:
622 static int getEmuDensity() {
623 return getDensityFromProperty("qemu.sf.lcd_density"); }
624 static int getBuildDensity() {
625 return getDensityFromProperty("ro.sf.lcd_density"); }
626 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700627
Dan Stoza7f7da322014-05-02 15:26:25 -0700628 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700629
Dan Stoza9e56aa02015-11-02 13:00:03 -0800630 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700631 DisplayInfo info = DisplayInfo();
632
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633 float xdpi = hwConfig->getDpiX();
634 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700635
636 if (type == DisplayDevice::DISPLAY_PRIMARY) {
637 // The density of the device is provided by a build property
638 float density = Density::getBuildDensity() / 160.0f;
639 if (density == 0) {
640 // the build doesn't provide a density -- this is wrong!
641 // use xdpi instead
642 ALOGE("ro.sf.lcd_density must be defined as a build property");
643 density = xdpi / 160.0f;
644 }
645 if (Density::getEmuDensity()) {
646 // if "qemu.sf.lcd_density" is specified, it overrides everything
647 xdpi = ydpi = density = Density::getEmuDensity();
648 density /= 160.0f;
649 }
650 info.density = density;
651
652 // TODO: this needs to go away (currently needed only by webkit)
653 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
654 info.orientation = hw->getOrientation();
655 } else {
656 // TODO: where should this value come from?
657 static const int TV_DENSITY = 213;
658 info.density = TV_DENSITY / 160.0f;
659 info.orientation = 0;
660 }
661
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662 info.w = hwConfig->getWidth();
663 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700664 info.xdpi = xdpi;
665 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800666 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700667 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668
Andy McFadden91b2ca82014-06-13 14:04:23 -0700669 // This is how far in advance a buffer must be queued for
670 // presentation at a given time. If you want a buffer to appear
671 // on the screen at time N, you must submit the buffer before
672 // (N - presentationDeadline).
673 //
674 // Normally it's one full refresh period (to give SF a chance to
675 // latch the buffer), but this can be reduced by configuring a
676 // DispSync offset. Any additional delays introduced by the hardware
677 // composer or panel must be accounted for here.
678 //
679 // We add an additional 1ms to allow for processing time and
680 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 info.presentationDeadline = hwConfig->getVsyncPeriod() -
682 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700683
684 // All non-virtual displays are currently considered secure.
685 info.secure = true;
686
Michael Wright28f24d02016-07-12 13:30:53 -0700687 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700688 }
689
Dan Stoza7f7da322014-05-02 15:26:25 -0700690 return NO_ERROR;
691}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700692
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800693status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700694 DisplayStatInfo* stats) {
695 if (stats == NULL) {
696 return BAD_VALUE;
697 }
698
699 // FIXME for now we always return stats for the primary display
700 memset(stats, 0, sizeof(*stats));
701 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
702 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
703 return NO_ERROR;
704}
705
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700706int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800707 if (display == NULL) {
708 ALOGE("%s : display is NULL", __func__);
709 return BAD_VALUE;
710 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700711 sp<DisplayDevice> device(getDisplayDevice(display));
712 if (device != NULL) {
713 return device->getActiveConfig();
714 }
715 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700716}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700717
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700718void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
719 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
720 this);
721 int32_t type = hw->getDisplayType();
722 int currentMode = hw->getActiveConfig();
723
724 if (mode == currentMode) {
725 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
726 return;
727 }
728
729 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
730 ALOGW("Trying to set config for virtual display");
731 return;
732 }
733
734 hw->setActiveConfig(mode);
735 getHwComposer().setActiveConfig(type, mode);
736}
737
738status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
739 class MessageSetActiveConfig: public MessageBase {
740 SurfaceFlinger& mFlinger;
741 sp<IBinder> mDisplay;
742 int mMode;
743 public:
744 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
745 int mode) :
746 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
747 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700748 Vector<DisplayInfo> configs;
749 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700750 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700751 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700752 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700753 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700754 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700755 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
756 if (hw == NULL) {
757 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700758 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700759 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
760 ALOGW("Attempt to set active config = %d for virtual display",
761 mMode);
762 } else {
763 mFlinger.setActiveConfigInternal(hw, mMode);
764 }
765 return true;
766 }
767 };
768 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
769 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700770 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700771}
Michael Wright28f24d02016-07-12 13:30:53 -0700772status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
773 Vector<android_color_mode_t>* outColorModes) {
774 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
775 return BAD_VALUE;
776 }
777
778 if (!display.get()) {
779 return NAME_NOT_FOUND;
780 }
781
782 int32_t type = NAME_NOT_FOUND;
783 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
784 if (display == mBuiltinDisplays[i]) {
785 type = i;
786 break;
787 }
788 }
789
790 if (type < 0) {
791 return type;
792 }
793
794 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
795 outColorModes->clear();
796 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
797
798 return NO_ERROR;
799}
800
801android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
802 sp<DisplayDevice> device(getDisplayDevice(display));
803 if (device != nullptr) {
804 return device->getActiveColorMode();
805 }
806 return static_cast<android_color_mode_t>(BAD_VALUE);
807}
808
809void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
810 android_color_mode_t mode) {
811 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
812 this);
813 int32_t type = hw->getDisplayType();
814 android_color_mode_t currentMode = hw->getActiveColorMode();
815
816 if (mode == currentMode) {
817 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
818 return;
819 }
820
821 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
822 ALOGW("Trying to set config for virtual display");
823 return;
824 }
825
826 hw->setActiveColorMode(mode);
827 getHwComposer().setActiveColorMode(type, mode);
828}
829
830
831status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
832 android_color_mode_t colorMode) {
833 class MessageSetActiveColorMode: public MessageBase {
834 SurfaceFlinger& mFlinger;
835 sp<IBinder> mDisplay;
836 android_color_mode_t mMode;
837 public:
838 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
839 android_color_mode_t mode) :
840 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
841 virtual bool handler() {
842 Vector<android_color_mode_t> modes;
843 mFlinger.getDisplayColorModes(mDisplay, &modes);
844 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
845 if (mMode < 0 || !exists) {
846 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
847 mDisplay.get());
848 return true;
849 }
850 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
851 if (hw == nullptr) {
852 ALOGE("Attempt to set active color mode = %d for null display %p",
853 mMode, mDisplay.get());
854 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
855 ALOGW("Attempt to set active color mode= %d for virtual display",
856 mMode);
857 } else {
858 mFlinger.setActiveColorModeInternal(hw, mMode);
859 }
860 return true;
861 }
862 };
863 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
864 postMessageSync(msg);
865 return NO_ERROR;
866}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700867
Svetoslavd85084b2014-03-20 10:28:31 -0700868status_t SurfaceFlinger::clearAnimationFrameStats() {
869 Mutex::Autolock _l(mStateLock);
870 mAnimFrameTracker.clearStats();
871 return NO_ERROR;
872}
873
874status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
875 Mutex::Autolock _l(mStateLock);
876 mAnimFrameTracker.getStats(outStats);
877 return NO_ERROR;
878}
879
Dan Stozac4f471e2016-03-24 09:31:08 -0700880status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
881 HdrCapabilities* outCapabilities) const {
882 Mutex::Autolock _l(mStateLock);
883
884 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
885 if (displayDevice == nullptr) {
886 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
887 return BAD_VALUE;
888 }
889
890 std::unique_ptr<HdrCapabilities> capabilities =
891 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
892 if (capabilities) {
893 std::swap(*outCapabilities, *capabilities);
894 } else {
895 return BAD_VALUE;
896 }
897
898 return NO_ERROR;
899}
900
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700901status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
902 if (enable == mInjectVSyncs) {
903 return NO_ERROR;
904 }
905
906 if (enable) {
907 mInjectVSyncs = enable;
908 ALOGV("VSync Injections enabled");
909 if (mVSyncInjector.get() == nullptr) {
910 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700911 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700912 }
913 mEventQueue.setEventThread(mInjectorEventThread);
914 } else {
915 mInjectVSyncs = enable;
916 ALOGV("VSync Injections disabled");
917 mEventQueue.setEventThread(mSFEventThread);
918 mVSyncInjector.clear();
919 }
920 return NO_ERROR;
921}
922
923status_t SurfaceFlinger::injectVSync(nsecs_t when) {
924 if (!mInjectVSyncs) {
925 ALOGE("VSync Injections not enabled");
926 return BAD_VALUE;
927 }
928 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
929 ALOGV("Injecting VSync inside SurfaceFlinger");
930 mVSyncInjector->onInjectSyncEvent(when);
931 }
932 return NO_ERROR;
933}
934
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800935// ----------------------------------------------------------------------------
936
937sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800938 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700939}
940
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800941// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800942
943void SurfaceFlinger::waitForEvent() {
944 mEventQueue.waitMessage();
945}
946
947void SurfaceFlinger::signalTransaction() {
948 mEventQueue.invalidate();
949}
950
951void SurfaceFlinger::signalLayerUpdate() {
952 mEventQueue.invalidate();
953}
954
955void SurfaceFlinger::signalRefresh() {
956 mEventQueue.refresh();
957}
958
959status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800960 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800961 return mEventQueue.postMessage(msg, reltime);
962}
963
964status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800965 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800966 status_t res = mEventQueue.postMessage(msg, reltime);
967 if (res == NO_ERROR) {
968 msg->wait();
969 }
970 return res;
971}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800972
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700973void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700974 do {
975 waitForEvent();
976 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977}
978
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700979void SurfaceFlinger::enableHardwareVsync() {
980 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700981 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700982 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700983 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
984 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700985 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700986 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700987}
988
Jesse Hall948fe0c2013-10-14 12:56:09 -0700989void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700990 Mutex::Autolock _l(mHWVsyncLock);
991
Jesse Hall948fe0c2013-10-14 12:56:09 -0700992 if (makeAvailable) {
993 mHWVsyncAvailable = true;
994 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700995 // Hardware vsync is not currently available, so abort the resync
996 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700997 return;
998 }
999
Dan Stoza9e56aa02015-11-02 13:00:03 -08001000 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1001 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001002
1003 mPrimaryDispSync.reset();
1004 mPrimaryDispSync.setPeriod(period);
1005
1006 if (!mPrimaryHWVsyncEnabled) {
1007 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001008 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1009 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001010 mPrimaryHWVsyncEnabled = true;
1011 }
1012}
1013
Jesse Hall948fe0c2013-10-14 12:56:09 -07001014void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001015 Mutex::Autolock _l(mHWVsyncLock);
1016 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001017 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1018 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001019 mPrimaryDispSync.endResync();
1020 mPrimaryHWVsyncEnabled = false;
1021 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001022 if (makeUnavailable) {
1023 mHWVsyncAvailable = false;
1024 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001025}
1026
Tim Murray4a4e4a22016-04-19 16:29:23 +00001027void SurfaceFlinger::resyncWithRateLimit() {
1028 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1029 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001030 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001031 }
1032}
1033
Dan Stoza9e56aa02015-11-02 13:00:03 -08001034void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001035 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001036
Jamie Gennisd1700752013-10-14 12:22:52 -07001037 { // Scope for the lock
1038 Mutex::Autolock _l(mHWVsyncLock);
1039 if (type == 0 && mPrimaryHWVsyncEnabled) {
1040 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001041 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001042 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001043
1044 if (needsHwVsync) {
1045 enableHardwareVsync();
1046 } else {
1047 disableHardwareVsync(false);
1048 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001049}
1050
Dan Stoza9e56aa02015-11-02 13:00:03 -08001051void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1052 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1053 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1054 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001055
Dan Stoza9e56aa02015-11-02 13:00:03 -08001056 // All non-virtual displays are currently considered secure.
1057 bool isSecure = true;
1058
1059 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1060 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1061 wp<IBinder> token = mBuiltinDisplays[type];
1062
1063 sp<IGraphicBufferProducer> producer;
1064 sp<IGraphicBufferConsumer> consumer;
1065 BufferQueue::createBufferQueue(&producer, &consumer,
1066 new GraphicBufferAlloc());
1067
1068 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1069 DisplayDevice::DISPLAY_PRIMARY, consumer);
1070 sp<DisplayDevice> hw = new DisplayDevice(this,
1071 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1072 producer, mRenderEngine->getEGLConfig());
1073 mDisplays.add(token, hw);
1074 } else {
1075 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001076 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001077 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001078 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001079 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001080 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1081 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001082 }
1083 setTransactionFlags(eDisplayTransactionNeeded);
1084
Andy McFadden9e9689c2012-10-10 18:17:51 -07001085 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001086 }
Mathias Agopian86303202012-07-24 22:46:10 -07001087}
1088
Dan Stoza9e56aa02015-11-02 13:00:03 -08001089void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001091 getHwComposer().setVsyncEnabled(disp,
1092 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001093}
1094
Mathias Agopian4fec8732012-06-29 14:12:52 -07001095void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001096 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001097 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001098 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001099 bool frameMissed = !mHadClientComposition &&
1100 mPreviousPresentFence != Fence::NO_FENCE &&
1101 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1102 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001103 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001104 signalLayerUpdate();
1105 break;
1106 }
1107
Dan Stoza6b9454d2014-11-07 16:00:59 -08001108 bool refreshNeeded = handleMessageTransaction();
1109 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001110 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001111 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001112 // Signal a refresh if a transaction modified the window state,
1113 // a new buffer was latched, or if HWC has requested a full
1114 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001115 signalRefresh();
1116 }
1117 break;
1118 }
1119 case MessageQueue::REFRESH: {
1120 handleMessageRefresh();
1121 break;
1122 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001123 }
1124}
1125
Dan Stoza6b9454d2014-11-07 16:00:59 -08001126bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001127 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001128 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001129 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001130 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001131 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001132 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001133}
1134
Dan Stoza6b9454d2014-11-07 16:00:59 -08001135bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001136 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001137 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001138}
1139
1140void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001141 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001142
Pablo Ceballos40845df2016-01-25 17:41:15 -08001143 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001144
Brian Andersond6927fb2016-07-23 23:37:30 -07001145 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001146 rebuildLayerStacks();
1147 setUpHWComposer();
1148 doDebugFlashRegions();
1149 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001150 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001151
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001152 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001153
1154 mHadClientComposition = false;
1155 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1156 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1157 mHadClientComposition = mHadClientComposition ||
1158 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1159 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001160
Dan Stoza9e56aa02015-11-02 13:00:03 -08001161 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001162}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001163
Mathias Agopiancd60f992012-08-16 16:28:27 -07001164void SurfaceFlinger::doDebugFlashRegions()
1165{
1166 // is debugging enabled
1167 if (CC_LIKELY(!mDebugRegion))
1168 return;
1169
1170 const bool repaintEverything = mRepaintEverything;
1171 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1172 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001173 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001174 // transform the dirty region into this screen's coordinate space
1175 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1176 if (!dirtyRegion.isEmpty()) {
1177 // redraw the whole screen
1178 doComposeSurfaces(hw, Region(hw->bounds()));
1179
1180 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001181 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001182 RenderEngine& engine(getRenderEngine());
1183 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1184
Mathias Agopianda27af92012-09-13 18:17:13 -07001185 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001186 }
1187 }
1188 }
1189
1190 postFramebuffer();
1191
1192 if (mDebugRegion > 1) {
1193 usleep(mDebugRegion * 1000);
1194 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001195
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001197 auto& displayDevice = mDisplays[displayId];
1198 if (!displayDevice->isDisplayOn()) {
1199 continue;
1200 }
1201
1202 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1204 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001205 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001206}
1207
Brian Andersond6927fb2016-07-23 23:37:30 -07001208void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001209{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001210 ATRACE_CALL();
1211 ALOGV("preComposition");
1212
Mathias Agopiancd60f992012-08-16 16:28:27 -07001213 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001214 const LayerVector& layers(mDrawingState.layersSortedByZ);
1215 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001216 for (size_t i=0 ; i<count ; i++) {
Brian Andersond6927fb2016-07-23 23:37:30 -07001217 if (layers[i]->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001218 needExtraInvalidate = true;
1219 }
1220 }
1221 if (needExtraInvalidate) {
1222 signalLayerUpdate();
1223 }
1224}
1225
Brian Andersond6927fb2016-07-23 23:37:30 -07001226void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001227{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 ATRACE_CALL();
1229 ALOGV("postComposition");
1230
Brian Anderson3546a3f2016-07-14 11:51:14 -07001231 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001232 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001233 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001234 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001235 }
1236
Brian Andersond6927fb2016-07-23 23:37:30 -07001237 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001238
1239 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1240 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1241 glCompositionDoneFenceTime =
1242 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1243 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1244 } else {
1245 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1246 }
1247 mGlCompositionDoneTimeline.updateSignalTimes();
1248
1249 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1250 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1251 mDisplayTimeline.push(displayFenceTime);
1252 mDisplayTimeline.updateSignalTimes();
1253
1254 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1255 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1256 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1257 presentFenceTime = &displayFenceTime;
1258 } else {
1259 retireFenceTime = &displayFenceTime;
1260 }
1261
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001262 const LayerVector& layers(mDrawingState.layersSortedByZ);
1263 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001264 for (size_t i=0 ; i<count ; i++) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001265 bool frameLatched =
1266 layers[i]->onPostComposition(glCompositionDoneFenceTime,
1267 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001268 if (frameLatched) {
1269 recordBufferingStats(layers[i]->getName().string(),
1270 layers[i]->getOccupancyHistory(false));
1271 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001272 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001273
Brian Anderson3d4039d2016-09-23 16:31:30 -07001274 if (displayFence->isValid()) {
1275 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276 enableHardwareVsync();
1277 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001278 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279 }
1280 }
1281
Andy McFadden5167ec62014-05-22 13:08:43 -07001282 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001283 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284 enableHardwareVsync();
1285 }
1286 }
1287
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001288 if (mAnimCompositionPending) {
1289 mAnimCompositionPending = false;
1290
Brian Anderson3d4039d2016-09-23 16:31:30 -07001291 if (displayFenceTime->isValid()) {
1292 mAnimFrameTracker.setActualPresentFence(
1293 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001294 } else {
1295 // The HWC doesn't support present fences, so use the refresh
1296 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001297 nsecs_t presentTime =
1298 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001299 mAnimFrameTracker.setActualPresentTime(presentTime);
1300 }
1301 mAnimFrameTracker.advanceFrame();
1302 }
Dan Stozab90cf072015-03-05 11:05:59 -08001303
1304 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1305 return;
1306 }
1307
1308 nsecs_t currentTime = systemTime();
1309 if (mHasPoweredOff) {
1310 mHasPoweredOff = false;
1311 } else {
1312 nsecs_t period = mPrimaryDispSync.getPeriod();
1313 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1314 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1315 if (numPeriods < NUM_BUCKETS - 1) {
1316 mFrameBuckets[numPeriods] += elapsedTime;
1317 } else {
1318 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1319 }
1320 mTotalTime += elapsedTime;
1321 }
1322 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001323}
1324
1325void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 ATRACE_CALL();
1327 ALOGV("rebuildLayerStacks");
1328
Mathias Agopiancd60f992012-08-16 16:28:27 -07001329 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001330 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001331 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001332 mVisibleRegionsDirty = false;
1333 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001334
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001335 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001336 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001337 Region opaqueRegion;
1338 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001339 Vector<sp<Layer>> layersSortedByZ;
1340 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1341 const Transform& tr(displayDevice->getTransform());
1342 const Rect bounds(displayDevice->getBounds());
1343 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001344 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001345 displayDevice->getLayerStack(), dirtyRegion,
1346 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001347
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001348 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001349 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001350 const sp<Layer>& layer(layers[i]);
1351 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001353 Region drawRegion(tr.transform(
1354 layer->visibleNonTransparentRegion));
1355 drawRegion.andSelf(bounds);
1356 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001357 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358 } else {
1359 // Clear out the HWC layer if this layer was
1360 // previously visible, but no longer is
1361 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1362 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001363 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001364 }
1365 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001366 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1368 displayDevice->undefinedRegion.set(bounds);
1369 displayDevice->undefinedRegion.subtractSelf(
1370 tr.transform(opaqueRegion));
1371 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001372 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001373 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001374}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001375
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 ATRACE_CALL();
1378 ALOGV("setUpHWComposer");
1379
Jesse Hall028dc8f2013-08-20 16:35:32 -07001380 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001381 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1382 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1383 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1384
1385 // If nothing has changed (!dirty), don't recompose.
1386 // If something changed, but we don't currently have any visible layers,
1387 // and didn't when we last did a composition, then skip it this time.
1388 // The second rule does two things:
1389 // - When all layers are removed from a display, we'll emit one black
1390 // frame, then nothing more until we get new layers.
1391 // - When a display is created with a private layer stack, we won't
1392 // emit any black frames until a layer is added to the layer stack.
1393 bool mustRecompose = dirty && !(empty && wasEmpty);
1394
1395 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1396 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1397 mustRecompose ? "doing" : "skipping",
1398 dirty ? "+" : "-",
1399 empty ? "+" : "-",
1400 wasEmpty ? "+" : "-");
1401
Dan Stoza71433162014-02-04 16:22:36 -08001402 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001403
1404 if (mustRecompose) {
1405 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1406 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001407 }
1408
Dan Stoza9e56aa02015-11-02 13:00:03 -08001409 // build the h/w work list
1410 if (CC_UNLIKELY(mGeometryInvalid)) {
1411 mGeometryInvalid = false;
1412 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1413 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1414 const auto hwcId = displayDevice->getHwcDisplayId();
1415 if (hwcId >= 0) {
1416 const Vector<sp<Layer>>& currentLayers(
1417 displayDevice->getVisibleLayersSortedByZ());
1418 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001419 for (size_t i = 0; i < currentLayers.size(); i++) {
1420 auto const& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001421 if (!layer->hasHwcLayer(hwcId)) {
1422 auto hwcLayer = mHwc->createLayer(hwcId);
1423 if (hwcLayer) {
1424 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1425 } else {
1426 layer->forceClientComposition(hwcId);
1427 foundLayerWithoutHwc = true;
1428 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001429 }
1430 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001431
Robert Carrae060832016-11-28 10:51:00 -08001432 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001433 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001435 }
1436 }
1437 }
1438 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001439 }
Riley Andrews03414a12014-07-01 14:22:59 -07001440
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001441
1442 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1443
Dan Stoza9e56aa02015-11-02 13:00:03 -08001444 // Set the per-frame data
1445 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1446 auto& displayDevice = mDisplays[displayId];
1447 const auto hwcId = displayDevice->getHwcDisplayId();
1448 if (hwcId < 0) {
1449 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001450 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001451 if (colorMatrix != mPreviousColorMatrix) {
1452 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1453 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1454 "display %zd: %d", displayId, result);
1455 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001456 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1457 layer->setPerFrameData(displayDevice);
1458 }
1459 }
1460
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001461 mPreviousColorMatrix = colorMatrix;
1462
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001464 auto& displayDevice = mDisplays[displayId];
1465 if (!displayDevice->isDisplayOn()) {
1466 continue;
1467 }
1468
1469 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001470 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1471 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001472 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001474
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475void SurfaceFlinger::doComposition() {
1476 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001477 ALOGV("doComposition");
1478
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001479 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001480 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001481 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001482 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001483 // transform the dirty region into this screen's coordinate space
1484 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001485
1486 // repaint the framebuffer (if needed)
1487 doDisplayComposition(hw, dirtyRegion);
1488
Mathias Agopiancd60f992012-08-16 16:28:27 -07001489 hw->dirtyRegion.clear();
1490 hw->flip(hw->swapRegion);
1491 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001492 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001493 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001494 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001495}
1496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001497void SurfaceFlinger::postFramebuffer()
1498{
Mathias Agopian841cde52012-03-01 15:44:37 -08001499 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001500 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001501
Mathias Agopiana44b0412011-10-16 18:46:35 -07001502 const nsecs_t now = systemTime();
1503 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001504
Dan Stoza9e56aa02015-11-02 13:00:03 -08001505 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1506 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001507 if (!displayDevice->isDisplayOn()) {
1508 continue;
1509 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 const auto hwcId = displayDevice->getHwcDisplayId();
1511 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001512 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001513 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001514 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001515 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1517 sp<Fence> releaseFence = Fence::NO_FENCE;
1518 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1519 releaseFence = displayDevice->getClientTargetAcquireFence();
1520 } else {
1521 auto hwcLayer = layer->getHwcLayer(hwcId);
1522 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001523 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001524 layer->onLayerDisplayed(releaseFence);
1525 }
1526 if (hwcId >= 0) {
1527 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001528 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001529 }
1530
Mathias Agopiana44b0412011-10-16 18:46:35 -07001531 mLastSwapBufferTime = systemTime() - now;
1532 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001533
1534 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1535 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1536 logFrameStats();
1537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001538}
1539
Mathias Agopian87baae12012-07-31 12:38:26 -07001540void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541{
Mathias Agopian841cde52012-03-01 15:44:37 -08001542 ATRACE_CALL();
1543
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001544 // here we keep a copy of the drawing state (that is the state that's
1545 // going to be overwritten by handleTransactionLocked()) outside of
1546 // mStateLock so that the side-effects of the State assignment
1547 // don't happen with mStateLock held (which can cause deadlocks).
1548 State drawingState(mDrawingState);
1549
Mathias Agopianca4d3602011-05-19 15:38:14 -07001550 Mutex::Autolock _l(mStateLock);
1551 const nsecs_t now = systemTime();
1552 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553
Mathias Agopianca4d3602011-05-19 15:38:14 -07001554 // Here we're guaranteed that some transaction flags are set
1555 // so we can call handleTransactionLocked() unconditionally.
1556 // We call getTransactionFlags(), which will also clear the flags,
1557 // with mStateLock held to guarantee that mCurrentState won't change
1558 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001559
Mathias Agopiane57f2922012-08-09 16:29:12 -07001560 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001561 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001562
Mathias Agopianca4d3602011-05-19 15:38:14 -07001563 mLastTransactionTime = systemTime() - now;
1564 mDebugInTransaction = 0;
1565 invalidateHwcGeometry();
1566 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001567}
1568
Mathias Agopian87baae12012-07-31 12:38:26 -07001569void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001570{
1571 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001572 const size_t count = currentLayers.size();
1573
Dan Stoza7dde5992015-05-22 09:51:44 -07001574 // Notify all layers of available frames
1575 for (size_t i = 0; i < count; ++i) {
1576 currentLayers[i]->notifyAvailableFrames();
1577 }
1578
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001579 /*
1580 * Traversal of the children
1581 * (perform the transaction for each of them if needed)
1582 */
1583
Mathias Agopian3559b072012-08-15 13:46:03 -07001584 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001585 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001586 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001587 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1588 if (!trFlags) continue;
1589
1590 const uint32_t flags = layer->doTransaction(0);
1591 if (flags & Layer::eVisibleRegion)
1592 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001593 }
1594 }
1595
1596 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001597 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001598 */
1599
Mathias Agopiane57f2922012-08-09 16:29:12 -07001600 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001601 // here we take advantage of Vector's copy-on-write semantics to
1602 // improve performance by skipping the transaction entirely when
1603 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001604 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1605 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001606 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001607 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001608 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001609 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001610
1611 // find the displays that were removed
1612 // (ie: in drawing state but not in current state)
1613 // also handle displays that changed
1614 // (ie: displays that are in both lists)
1615 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001616 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1617 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001618 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001619 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001620 // Call makeCurrent() on the primary display so we can
1621 // be sure that nothing associated with this display
1622 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001623 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001624 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001625 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1626 if (hw != NULL)
1627 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001628 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001629 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001630 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001631 } else {
1632 ALOGW("trying to remove the main display");
1633 }
1634 } else {
1635 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001636 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001637 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001638 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1639 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001640 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001641 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001642 // recreating the DisplayDevice, so we just remove it
1643 // from the drawing state, so that it get re-added
1644 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001645 sp<DisplayDevice> hw(getDisplayDevice(display));
1646 if (hw != NULL)
1647 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001648 mDisplays.removeItem(display);
1649 mDrawingState.displays.removeItemsAt(i);
1650 dc--; i--;
1651 // at this point we must loop to the next item
1652 continue;
1653 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001654
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001655 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001656 if (disp != NULL) {
1657 if (state.layerStack != draw[i].layerStack) {
1658 disp->setLayerStack(state.layerStack);
1659 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001660 if ((state.orientation != draw[i].orientation)
1661 || (state.viewport != draw[i].viewport)
1662 || (state.frame != draw[i].frame))
1663 {
1664 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001665 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001666 }
Michael Lentine47e45402014-07-18 15:34:25 -07001667 if (state.width != draw[i].width || state.height != draw[i].height) {
1668 disp->setDisplaySize(state.width, state.height);
1669 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001670 }
1671 }
1672 }
1673
1674 // find displays that were added
1675 // (ie: in current state but not in drawing state)
1676 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001677 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001678 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001679
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001680 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001681 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001682 sp<IGraphicBufferProducer> bqProducer;
1683 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001684 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1685 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001686
Dan Stoza9e56aa02015-11-02 13:00:03 -08001687 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001688 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001689 // Virtual displays without a surface are dormant:
1690 // they have external state (layer stack, projection,
1691 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001692 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001693
Dan Stoza8cf150a2016-08-02 10:27:31 -07001694 if (mUseHwcVirtualDisplays) {
1695 int width = 0;
1696 int status = state.surface->query(
1697 NATIVE_WINDOW_WIDTH, &width);
1698 ALOGE_IF(status != NO_ERROR,
1699 "Unable to query width (%d)", status);
1700 int height = 0;
1701 status = state.surface->query(
1702 NATIVE_WINDOW_HEIGHT, &height);
1703 ALOGE_IF(status != NO_ERROR,
1704 "Unable to query height (%d)", status);
1705 int intFormat = 0;
1706 status = state.surface->query(
1707 NATIVE_WINDOW_FORMAT, &intFormat);
1708 ALOGE_IF(status != NO_ERROR,
1709 "Unable to query format (%d)", status);
1710 auto format = static_cast<android_pixel_format_t>(
1711 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001712
Dan Stoza8cf150a2016-08-02 10:27:31 -07001713 mHwc->allocateVirtualDisplay(width, height, &format,
1714 &hwcId);
1715 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716
Dan Stoza5cf424b2016-05-20 14:02:39 -07001717 // TODO: Plumb requested format back up to consumer
1718
Dan Stoza9e56aa02015-11-02 13:00:03 -08001719 sp<VirtualDisplaySurface> vds =
1720 new VirtualDisplaySurface(*mHwc,
1721 hwcId, state.surface, bqProducer,
1722 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001723
1724 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001725 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001726 }
1727 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001728 ALOGE_IF(state.surface!=NULL,
1729 "adding a supported display, but rendering "
1730 "surface is provided (%p), ignoring it",
1731 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1733 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1734 dispSurface = new FramebufferSurface(*mHwc,
1735 DisplayDevice::DISPLAY_EXTERNAL,
1736 bqConsumer);
1737 producer = bqProducer;
1738 } else {
1739 ALOGE("Attempted to add non-external non-virtual"
1740 " display");
1741 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001742 }
1743
1744 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001745 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001746 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 state.type, hwcId, state.isSecure, display,
1748 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001749 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001750 hw->setLayerStack(state.layerStack);
1751 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001752 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001753 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001754 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001756 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001757 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001758 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001759 }
1760 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001761 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001762 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001763
Mathias Agopian84300952012-11-21 16:02:13 -08001764 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1765 // The transform hint might have changed for some layers
1766 // (either because a display has changed, or because a layer
1767 // as changed).
1768 //
1769 // Walk through all the layers in currentLayers,
1770 // and update their transform hint.
1771 //
1772 // If a layer is visible only on a single display, then that
1773 // display is used to calculate the hint, otherwise we use the
1774 // default display.
1775 //
1776 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1777 // the hint is set before we acquire a buffer from the surface texture.
1778 //
1779 // NOTE: layer transactions have taken place already, so we use their
1780 // drawing state. However, SurfaceFlinger's own transaction has not
1781 // happened yet, so we must use the current state layer list
1782 // (soon to become the drawing state list).
1783 //
1784 sp<const DisplayDevice> disp;
1785 uint32_t currentlayerStack = 0;
1786 for (size_t i=0; i<count; i++) {
1787 // NOTE: we rely on the fact that layers are sorted by
1788 // layerStack first (so we don't have to traverse the list
1789 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001790 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001791 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001792 if (i==0 || currentlayerStack != layerStack) {
1793 currentlayerStack = layerStack;
1794 // figure out if this layerstack is mirrored
1795 // (more than one display) if so, pick the default display,
1796 // if not, pick the only display it's on.
1797 disp.clear();
1798 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1799 sp<const DisplayDevice> hw(mDisplays[dpy]);
1800 if (hw->getLayerStack() == currentlayerStack) {
1801 if (disp == NULL) {
1802 disp = hw;
1803 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001804 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001805 break;
1806 }
1807 }
1808 }
1809 }
Chet Haase91d25932013-04-11 15:24:55 -07001810 if (disp == NULL) {
1811 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1812 // redraw after transform hint changes. See bug 8508397.
1813
1814 // could be null when this layer is using a layerStack
1815 // that is not visible on any display. Also can occur at
1816 // screen off/on times.
1817 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001818 }
Chet Haase91d25932013-04-11 15:24:55 -07001819 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001820 }
1821 }
1822
1823
Mathias Agopian3559b072012-08-15 13:46:03 -07001824 /*
1825 * Perform our own transaction if needed
1826 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001827
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001828 const LayerVector& layers(mDrawingState.layersSortedByZ);
1829 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001830 // layers have been added
1831 mVisibleRegionsDirty = true;
1832 }
1833
1834 // some layers might have been removed, so
1835 // we need to update the regions they're exposing.
1836 if (mLayersRemoved) {
1837 mLayersRemoved = false;
1838 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001839 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001840 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001841 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001842 if (currentLayers.indexOf(layer) < 0) {
1843 // this layer is not visible anymore
1844 // TODO: we could traverse the tree from front to back and
1845 // compute the actual visible region
1846 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001847 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001848 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001849 Region(Rect(s.active.w, s.active.h)));
1850 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001851 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001852 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853 }
1854
1855 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001856
1857 updateCursorAsync();
1858}
1859
1860void SurfaceFlinger::updateCursorAsync()
1861{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1863 auto& displayDevice = mDisplays[displayId];
1864 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001865 continue;
1866 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867
1868 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1869 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001870 }
1871 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001872}
1873
1874void SurfaceFlinger::commitTransaction()
1875{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001876 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001877 // Notify removed layers now that they can't be drawn from
1878 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001879 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1880 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001881 mLayersPendingRemoval[i]->onRemoved();
1882 }
1883 mLayersPendingRemoval.clear();
1884 }
1885
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001886 // If this transaction is part of a window animation then the next frame
1887 // we composite should be considered an animation as well.
1888 mAnimCompositionPending = mAnimTransactionPending;
1889
Mathias Agopian4fec8732012-06-29 14:12:52 -07001890 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001891 mTransactionPending = false;
1892 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001893 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001894}
1895
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001896void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001897 const LayerVector& currentLayers, uint32_t layerStack,
1898 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899{
Mathias Agopian841cde52012-03-01 15:44:37 -08001900 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001902
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001903 Region aboveOpaqueLayers;
1904 Region aboveCoveredLayers;
1905 Region dirty;
1906
Mathias Agopian87baae12012-07-31 12:38:26 -07001907 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001908
1909 size_t i = currentLayers.size();
1910 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001911 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001912
1913 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001914 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001915
Jesse Hall01e29052013-02-19 16:13:35 -08001916 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001917 if (s.layerStack != layerStack)
1918 continue;
1919
Mathias Agopianab028732010-03-16 16:41:46 -07001920 /*
1921 * opaqueRegion: area of a surface that is fully opaque.
1922 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001923 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001924
1925 /*
1926 * visibleRegion: area of a surface that is visible on screen
1927 * and not fully transparent. This is essentially the layer's
1928 * footprint minus the opaque regions above it.
1929 * Areas covered by a translucent surface are considered visible.
1930 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001932
1933 /*
1934 * coveredRegion: area of a surface that is covered by all
1935 * visible regions above it (which includes the translucent areas).
1936 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001937 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001938
Jesse Halla8026d22012-09-25 13:25:04 -07001939 /*
1940 * transparentRegion: area of a surface that is hinted to be completely
1941 * transparent. This is only used to tell when the layer has no visible
1942 * non-transparent regions and can be removed from the layer list. It
1943 * does not affect the visibleRegion of this layer or any layers
1944 * beneath it. The hint may not be correct if apps don't respect the
1945 * SurfaceView restrictions (which, sadly, some don't).
1946 */
1947 Region transparentRegion;
1948
Mathias Agopianab028732010-03-16 16:41:46 -07001949
1950 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001951 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001952 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001953 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001954 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001955 if (!visibleRegion.isEmpty()) {
1956 // Remove the transparent area from the visible region
1957 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001958 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001959 if (tr.preserveRects()) {
1960 // transform the transparent region
1961 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001963 // transformation too complex, can't do the
1964 // transparent region optimization.
1965 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001966 }
Mathias Agopianab028732010-03-16 16:41:46 -07001967 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968
Mathias Agopianab028732010-03-16 16:41:46 -07001969 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001970 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001972 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1973 // the opaque region is the layer's footprint
1974 opaqueRegion = visibleRegion;
1975 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976 }
1977 }
1978
Mathias Agopianab028732010-03-16 16:41:46 -07001979 // Clip the covered region to the visible region
1980 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1981
1982 // Update aboveCoveredLayers for next (lower) layer
1983 aboveCoveredLayers.orSelf(visibleRegion);
1984
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985 // subtract the opaque region covered by the layers above us
1986 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987
1988 // compute this layer's dirty region
1989 if (layer->contentDirty) {
1990 // we need to invalidate the whole region
1991 dirty = visibleRegion;
1992 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001993 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001994 layer->contentDirty = false;
1995 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001996 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001997 * the exposed region consists of two components:
1998 * 1) what's VISIBLE now and was COVERED before
1999 * 2) what's EXPOSED now less what was EXPOSED before
2000 *
2001 * note that (1) is conservative, we start with the whole
2002 * visible region but only keep what used to be covered by
2003 * something -- which mean it may have been exposed.
2004 *
2005 * (2) handles areas that were not covered by anything but got
2006 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002007 */
Mathias Agopianab028732010-03-16 16:41:46 -07002008 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009 const Region oldVisibleRegion = layer->visibleRegion;
2010 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002011 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2012 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002013 }
2014 dirty.subtractSelf(aboveOpaqueLayers);
2015
2016 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002017 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018
Mathias Agopianab028732010-03-16 16:41:46 -07002019 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002021
Jesse Halla8026d22012-09-25 13:25:04 -07002022 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 layer->setVisibleRegion(visibleRegion);
2024 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002025 layer->setVisibleNonTransparentRegion(
2026 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027 }
2028
Mathias Agopian87baae12012-07-31 12:38:26 -07002029 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002030}
2031
Mathias Agopian87baae12012-07-31 12:38:26 -07002032void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2033 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002034 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002035 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2036 if (hw->getLayerStack() == layerStack) {
2037 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002038 }
2039 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002040}
2041
Dan Stoza6b9454d2014-11-07 16:00:59 -08002042bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 ALOGV("handlePageFlip");
2045
Brian Andersond6927fb2016-07-23 23:37:30 -07002046 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047
Mathias Agopian4fec8732012-06-29 14:12:52 -07002048 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002049 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002050 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002051
2052 // Store the set of layers that need updates. This set must not change as
2053 // buffers are being latched, as this could result in a deadlock.
2054 // Example: Two producers share the same command stream and:
2055 // 1.) Layer 0 is latched
2056 // 2.) Layer 0 gets a new frame
2057 // 2.) Layer 1 gets a new frame
2058 // 3.) Layer 1 is latched.
2059 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2060 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002061 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002062 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002063 if (layer->hasQueuedFrame()) {
2064 frameQueued = true;
2065 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002067 } else {
2068 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002069 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002070 } else {
2071 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002072 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002073 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002075 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002076 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002077 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002078 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002079 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002080
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002081 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002082
2083 // If we will need to wake up at some time in the future to deal with a
2084 // queued frame that shouldn't be displayed during this vsync period, wake
2085 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002087 signalLayerUpdate();
2088 }
2089
2090 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002091 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002092}
2093
Mathias Agopianad456f92011-01-13 17:53:01 -08002094void SurfaceFlinger::invalidateHwcGeometry()
2095{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002097}
2098
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002099
Fabien Sanglard830b8472016-11-30 16:35:58 -08002100void SurfaceFlinger::doDisplayComposition(
2101 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103{
Dan Stoza71433162014-02-04 16:22:36 -08002104 // We only need to actually compose the display if:
2105 // 1) It is being handled by hardware composer, which may need this to
2106 // keep its virtual display state machine in sync, or
2107 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002108 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002109 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002110 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002111 return;
2112 }
2113
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 ALOGV("doDisplayComposition");
2115
Mathias Agopian87baae12012-07-31 12:38:26 -07002116 Region dirtyRegion(inDirtyRegion);
2117
Mathias Agopianb8a55602009-06-26 19:06:36 -07002118 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002119 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002120
Fabien Sanglard830b8472016-11-30 16:35:58 -08002121 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002122 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002123 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2124 // takes a rectangle, we must make sure to update that whole
2125 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002126 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002127 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002128 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002129 // We need to redraw the rectangle that will be updated
2130 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002131 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002132 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002133 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002134 } else {
2135 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002136 dirtyRegion.set(displayDevice->bounds());
2137 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 }
2139 }
2140
Fabien Sanglard830b8472016-11-30 16:35:58 -08002141 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002143 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002144 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002145
2146 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002147 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148}
2149
Dan Stoza9e56aa02015-11-02 13:00:03 -08002150bool SurfaceFlinger::doComposeSurfaces(
2151 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002152{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002153 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002154
Dan Stoza9e56aa02015-11-02 13:00:03 -08002155 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002156
2157 mat4 oldColorMatrix;
2158 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2159 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2160 if (applyColorMatrix) {
2161 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2162 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2163 }
2164
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2166 if (hasClientComposition) {
2167 ALOGV("hasClientComposition");
2168
2169 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002170 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002172 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2173 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2174 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2175 }
2176 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002177 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002178
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002179 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2181 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002182 // when using overlays, we assume a fully transparent framebuffer
2183 // NOTE: we could reduce how much we need to clear, for instance
2184 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002185 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002186 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002188 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002189 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002191
2192 // we remove the scissor part
2193 // we're left with the letterbox region
2194 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002196
2197 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002199
2200 // but limit it to the dirty region
2201 region.andSelf(dirty);
2202
Mathias Agopianb9494d52012-04-18 02:28:45 -07002203 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002204 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002205 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002207 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002208 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002209
Dan Stoza9e56aa02015-11-02 13:00:03 -08002210 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002211 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002212 // scissor on the main display. It should never be needed
2213 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214 const Rect& bounds(displayDevice->getBounds());
2215 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002216 if (scissor != bounds) {
2217 // scissor doesn't match the screen's dimensions, so we
2218 // need to clear everything outside of it and enable
2219 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002220
Mathias Agopianf45c5102012-10-24 16:29:17 -07002221 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002222 const uint32_t height = displayDevice->getHeight();
2223 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002224 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002225 }
2226 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002227 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002228
Mathias Agopian85d751c2012-08-29 16:59:24 -07002229 /*
2230 * and then, render the layers targeted at the framebuffer
2231 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002232
Dan Stoza9e56aa02015-11-02 13:00:03 -08002233 ALOGV("Rendering client layers");
2234 const Transform& displayTransform = displayDevice->getTransform();
2235 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002236 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 bool firstLayer = true;
2238 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2239 const Region clip(dirty.intersect(
2240 displayTransform.transform(layer->visibleRegion)));
2241 ALOGV("Layer: %s", layer->getName().string());
2242 ALOGV(" Composition type: %s",
2243 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002244 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002245 switch (layer->getCompositionType(hwcId)) {
2246 case HWC2::Composition::Cursor:
2247 case HWC2::Composition::Device:
2248 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002249 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002250 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2251 layer->isOpaque(state) && (state.alpha == 1.0f)
2252 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002253 // never clear the very first layer since we're
2254 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002255 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002256 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002257 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002258 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 case HWC2::Composition::Client: {
2260 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002261 break;
2262 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002263 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002264 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002265 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002266 } else {
2267 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002268 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002269 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002270 }
2271 } else {
2272 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002273 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002274 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002276 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002277 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002278 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002279 }
2280 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002281
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002282 if (applyColorMatrix) {
2283 getRenderEngine().setupColorTransform(oldColorMatrix);
2284 }
2285
Mathias Agopianf45c5102012-10-24 16:29:17 -07002286 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002288 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289}
2290
Fabien Sanglard830b8472016-11-30 16:35:58 -08002291void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2292 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002293 RenderEngine& engine(getRenderEngine());
2294 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295}
2296
Dan Stoza7d89d062015-04-30 13:29:25 -07002297status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002298 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002299 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002300 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002301{
Dan Stoza7d89d062015-04-30 13:29:25 -07002302 // add this layer to the current state list
2303 {
2304 Mutex::Autolock _l(mStateLock);
2305 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2306 return NO_MEMORY;
2307 }
2308 mCurrentState.layersSortedByZ.add(lbc);
2309 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2310 }
2311
Mathias Agopian96f08192010-06-02 23:28:45 -07002312 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002313 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002314
Dan Stoza7d89d062015-04-30 13:29:25 -07002315 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002316}
2317
Dan Stoza22851c32016-08-09 13:21:03 -07002318status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002320 sp<Layer> layer = weakLayer.promote();
2321 if (layer == nullptr) {
2322 // The layer has already been removed, carry on
2323 return NO_ERROR;
2324 }
2325
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002326 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2327 if (index >= 0) {
2328 mLayersPendingRemoval.push(layer);
2329 mLayersRemoved = true;
2330 setTransactionFlags(eTransactionNeeded);
2331 return NO_ERROR;
2332 }
2333 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002334}
2335
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002336uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002337 return android_atomic_release_load(&mTransactionFlags);
2338}
2339
Mathias Agopian3f844832013-08-07 21:24:32 -07002340uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2342}
2343
Mathias Agopian3f844832013-08-07 21:24:32 -07002344uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2346 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002347 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348 }
2349 return old;
2350}
2351
Mathias Agopian8b33f032012-07-24 20:43:54 -07002352void SurfaceFlinger::setTransactionState(
2353 const Vector<ComposerState>& state,
2354 const Vector<DisplayState>& displays,
2355 uint32_t flags)
2356{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002357 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002358 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002359 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002360
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002361 if (flags & eAnimation) {
2362 // For window updates that are part of an animation we must wait for
2363 // previous animation "frames" to be handled.
2364 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002365 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002366 if (CC_UNLIKELY(err != NO_ERROR)) {
2367 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002368 // caller after a few seconds.
2369 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2370 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002371 mAnimTransactionPending = false;
2372 break;
2373 }
2374 }
2375 }
2376
Mathias Agopiane57f2922012-08-09 16:29:12 -07002377 size_t count = displays.size();
2378 for (size_t i=0 ; i<count ; i++) {
2379 const DisplayState& s(displays[i]);
2380 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002381 }
2382
Mathias Agopiane57f2922012-08-09 16:29:12 -07002383 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002384 for (size_t i=0 ; i<count ; i++) {
2385 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002386 // Here we need to check that the interface we're given is indeed
2387 // one of our own. A malicious client could give us a NULL
2388 // IInterface, or one of its own or even one of our own but a
2389 // different type. All these situations would cause us to crash.
2390 //
2391 // NOTE: it would be better to use RTTI as we could directly check
2392 // that we have a Client*. however, RTTI is disabled in Android.
2393 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002394 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002395 if (binder != NULL) {
2396 String16 desc(binder->getInterfaceDescriptor());
2397 if (desc == ISurfaceComposerClient::descriptor) {
2398 sp<Client> client( static_cast<Client *>(s.client.get()) );
2399 transactionFlags |= setClientStateLocked(client, s.state);
2400 }
2401 }
2402 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002403 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002404
Robert Carr2a7dbb42016-05-24 11:41:28 -07002405 // If a synchronous transaction is explicitly requested without any changes,
2406 // force a transaction anyway. This can be used as a flush mechanism for
2407 // previous async transactions.
2408 if (transactionFlags == 0 && (flags & eSynchronous)) {
2409 transactionFlags = eTransactionNeeded;
2410 }
2411
Mathias Agopian386aa982011-11-07 21:58:03 -08002412 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002413 if (mInterceptor.isEnabled()) {
2414 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2415 }
Irvel468051e2016-06-13 16:44:44 -07002416
Mathias Agopian386aa982011-11-07 21:58:03 -08002417 // this triggers the transaction
2418 setTransactionFlags(transactionFlags);
2419
2420 // if this is a synchronous transaction, wait for it to take effect
2421 // before returning.
2422 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002423 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002424 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002425 if (flags & eAnimation) {
2426 mAnimTransactionPending = true;
2427 }
2428 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002429 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2430 if (CC_UNLIKELY(err != NO_ERROR)) {
2431 // just in case something goes wrong in SF, return to the
2432 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002433 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2434 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002435 break;
2436 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002437 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 }
2439}
2440
Mathias Agopiane57f2922012-08-09 16:29:12 -07002441uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2442{
Jesse Hall9a143922012-10-04 16:29:19 -07002443 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2444 if (dpyIdx < 0)
2445 return 0;
2446
Mathias Agopiane57f2922012-08-09 16:29:12 -07002447 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002448 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002449 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002450 const uint32_t what = s.what;
2451 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002452 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002453 disp.surface = s.surface;
2454 flags |= eDisplayTransactionNeeded;
2455 }
2456 }
2457 if (what & DisplayState::eLayerStackChanged) {
2458 if (disp.layerStack != s.layerStack) {
2459 disp.layerStack = s.layerStack;
2460 flags |= eDisplayTransactionNeeded;
2461 }
2462 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002463 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002464 if (disp.orientation != s.orientation) {
2465 disp.orientation = s.orientation;
2466 flags |= eDisplayTransactionNeeded;
2467 }
2468 if (disp.frame != s.frame) {
2469 disp.frame = s.frame;
2470 flags |= eDisplayTransactionNeeded;
2471 }
2472 if (disp.viewport != s.viewport) {
2473 disp.viewport = s.viewport;
2474 flags |= eDisplayTransactionNeeded;
2475 }
2476 }
Michael Lentine47e45402014-07-18 15:34:25 -07002477 if (what & DisplayState::eDisplaySizeChanged) {
2478 if (disp.width != s.width) {
2479 disp.width = s.width;
2480 flags |= eDisplayTransactionNeeded;
2481 }
2482 if (disp.height != s.height) {
2483 disp.height = s.height;
2484 flags |= eDisplayTransactionNeeded;
2485 }
2486 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002487 }
2488 return flags;
2489}
2490
2491uint32_t SurfaceFlinger::setClientStateLocked(
2492 const sp<Client>& client,
2493 const layer_state_t& s)
2494{
2495 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002496 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (layer != 0) {
2498 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002499 bool geometryAppliesWithResize =
2500 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002501 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002502 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002504 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002505 }
2506 if (what & layer_state_t::eLayerChanged) {
2507 // NOTE: index needs to be calculated before we update the state
2508 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002509 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002510 mCurrentState.layersSortedByZ.removeAt(idx);
2511 mCurrentState.layersSortedByZ.add(layer);
2512 // we need traversal (state changed)
2513 // AND transaction (list changed)
2514 flags |= eTransactionNeeded|eTraversalNeeded;
2515 }
2516 }
2517 if (what & layer_state_t::eSizeChanged) {
2518 if (layer->setSize(s.w, s.h)) {
2519 flags |= eTraversalNeeded;
2520 }
2521 }
2522 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002524 flags |= eTraversalNeeded;
2525 }
2526 if (what & layer_state_t::eMatrixChanged) {
2527 if (layer->setMatrix(s.matrix))
2528 flags |= eTraversalNeeded;
2529 }
2530 if (what & layer_state_t::eTransparentRegionChanged) {
2531 if (layer->setTransparentRegionHint(s.transparentRegion))
2532 flags |= eTraversalNeeded;
2533 }
Dan Stoza23116082015-06-18 14:58:39 -07002534 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002535 if (layer->setFlags(s.flags, s.mask))
2536 flags |= eTraversalNeeded;
2537 }
2538 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002539 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002540 flags |= eTraversalNeeded;
2541 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002542 if (what & layer_state_t::eFinalCropChanged) {
2543 if (layer->setFinalCrop(s.finalCrop))
2544 flags |= eTraversalNeeded;
2545 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002546 if (what & layer_state_t::eLayerStackChanged) {
2547 // NOTE: index needs to be calculated before we update the state
2548 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002549 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002550 mCurrentState.layersSortedByZ.removeAt(idx);
2551 mCurrentState.layersSortedByZ.add(layer);
2552 // we need traversal (state changed)
2553 // AND transaction (list changed)
2554 flags |= eTransactionNeeded|eTraversalNeeded;
2555 }
2556 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002557 if (what & layer_state_t::eDeferTransaction) {
2558 layer->deferTransactionUntil(s.handle, s.frameNumber);
2559 // We don't trigger a traversal here because if no other state is
2560 // changed, we don't want this to cause any more work
2561 }
Robert Carrc3574f72016-03-24 12:19:32 -07002562 if (what & layer_state_t::eOverrideScalingModeChanged) {
2563 layer->setOverrideScalingMode(s.overrideScalingMode);
2564 // We don't trigger a traversal here because if no other state is
2565 // changed, we don't want this to cause any more work
2566 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002567 }
2568 return flags;
2569}
2570
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002571status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002572 const String8& name,
2573 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002574 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2575 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002577 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002578 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002579 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002580 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002581 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002582
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002583 status_t result = NO_ERROR;
2584
2585 sp<Layer> layer;
2586
Mathias Agopian3165cc22012-08-08 19:42:09 -07002587 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2588 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002589 result = createNormalLayer(client,
2590 name, w, h, flags, format,
2591 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002593 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002594 result = createDimLayer(client,
2595 name, w, h, flags,
2596 handle, gbp, &layer);
2597 break;
2598 default:
2599 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002600 break;
2601 }
2602
Dan Stoza7d89d062015-04-30 13:29:25 -07002603 if (result != NO_ERROR) {
2604 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002606
2607 result = addClientLayer(client, *handle, *gbp, layer);
2608 if (result != NO_ERROR) {
2609 return result;
2610 }
Irvelffc9efc2016-07-27 15:16:37 -07002611 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002612
2613 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002614 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615}
2616
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002617status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2618 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2619 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620{
2621 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002622 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002623 case PIXEL_FORMAT_TRANSPARENT:
2624 case PIXEL_FORMAT_TRANSLUCENT:
2625 format = PIXEL_FORMAT_RGBA_8888;
2626 break;
2627 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002628 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 break;
2630 }
2631
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002632 *outLayer = new Layer(this, client, name, w, h, flags);
2633 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2634 if (err == NO_ERROR) {
2635 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002636 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002638
2639 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2640 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641}
2642
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002643status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2644 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2645 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002647 *outLayer = new LayerDim(this, client, name, w, h, flags);
2648 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002649 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002650 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002651}
2652
Mathias Agopianac9fa422013-02-11 16:40:36 -08002653status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002654{
Mathias Agopian67106042013-03-14 19:18:13 -07002655 // called by the window manager when it wants to remove a Layer
2656 status_t err = NO_ERROR;
2657 sp<Layer> l(client->getLayerUser(handle));
2658 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002659 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002660 err = removeLayer(l);
2661 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2662 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002663 }
2664 return err;
2665}
2666
Mathias Agopian13127d82013-03-05 17:47:11 -08002667status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002668{
Mathias Agopian67106042013-03-14 19:18:13 -07002669 // called by ~LayerCleaner() when all references to the IBinder (handle)
2670 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002671 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672}
2673
Mathias Agopianb60314a2012-04-10 22:09:54 -07002674// ---------------------------------------------------------------------------
2675
Andy McFadden13a082e2012-08-24 10:16:42 -07002676void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002677 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002678 Vector<ComposerState> state;
2679 Vector<DisplayState> displays;
2680 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002681 d.what = DisplayState::eDisplayProjectionChanged |
2682 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002683 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002684 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002685 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002686 d.frame.makeInvalid();
2687 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002688 d.width = 0;
2689 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002690 displays.add(d);
2691 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002692 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002693
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2695 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002696 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002697}
2698
2699void SurfaceFlinger::initializeDisplays() {
2700 class MessageScreenInitialized : public MessageBase {
2701 SurfaceFlinger* flinger;
2702 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002703 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002704 virtual bool handler() {
2705 flinger->onInitializeDisplays();
2706 return true;
2707 }
2708 };
2709 sp<MessageBase> msg = new MessageScreenInitialized(this);
2710 postMessageAsync(msg); // we may be called from main thread, use async message
2711}
2712
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002713void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2714 int mode) {
2715 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2716 this);
2717 int32_t type = hw->getDisplayType();
2718 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002719
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002720 if (mode == currentMode) {
2721 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002722 return;
2723 }
2724
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002725 hw->setPowerMode(mode);
2726 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2727 ALOGW("Trying to set power mode for virtual display");
2728 return;
2729 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002730
Irvelffc9efc2016-07-27 15:16:37 -07002731 if (mInterceptor.isEnabled()) {
2732 Mutex::Autolock _l(mStateLock);
2733 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2734 if (idx < 0) {
2735 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2736 return;
2737 }
2738 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2739 }
2740
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002741 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002742 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002743 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002744 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2745 // FIXME: eventthread only knows about the main display right now
2746 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002747 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002748 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002750 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002751 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002752 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002753
2754 struct sched_param param = {0};
2755 param.sched_priority = 1;
2756 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2757 ALOGW("Couldn't set SCHED_FIFO on display on");
2758 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002759 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002760 // Turn off the display
2761 struct sched_param param = {0};
2762 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2763 ALOGW("Couldn't set SCHED_OTHER on display off");
2764 }
2765
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002766 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002767 disableHardwareVsync(true); // also cancels any in-progress resync
2768
Mathias Agopiancde87a32012-09-13 14:09:01 -07002769 // FIXME: eventthread only knows about the main display right now
2770 mEventThread->onScreenReleased();
2771 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002772
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002773 getHwComposer().setPowerMode(type, mode);
2774 mVisibleRegionsDirty = true;
2775 // from this point on, SF will stop drawing on this display
2776 } else {
2777 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002778 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002779}
2780
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002781void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2782 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002783 SurfaceFlinger& mFlinger;
2784 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002785 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002786 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002787 MessageSetPowerMode(SurfaceFlinger& flinger,
2788 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2789 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002790 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002791 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002792 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002793 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002794 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002795 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002796 ALOGW("Attempt to set power mode = %d for virtual display",
2797 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002798 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002799 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002800 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002801 return true;
2802 }
2803 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002804 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002805 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002806}
2807
2808// ---------------------------------------------------------------------------
2809
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2811{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002813
Mathias Agopianbd115332013-04-18 16:41:04 -07002814 IPCThreadState* ipc = IPCThreadState::self();
2815 const int pid = ipc->getCallingPid();
2816 const int uid = ipc->getCallingUid();
2817 if ((uid != AID_SHELL) &&
2818 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002819 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002820 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002821 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002822 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002823 // (this would indicate SF is stuck, but we want to be able to
2824 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002825 status_t err = mStateLock.timedLock(s2ns(1));
2826 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002827 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002828 result.appendFormat(
2829 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2830 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002831 }
2832
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002833 bool dumpAll = true;
2834 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002835 size_t numArgs = args.size();
2836 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002837 if ((index < numArgs) &&
2838 (args[index] == String16("--list"))) {
2839 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002840 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002841 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002842 }
2843
2844 if ((index < numArgs) &&
2845 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002846 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002847 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002848 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002849 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002850
2851 if ((index < numArgs) &&
2852 (args[index] == String16("--latency-clear"))) {
2853 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002854 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002855 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002856 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002857
2858 if ((index < numArgs) &&
2859 (args[index] == String16("--dispsync"))) {
2860 index++;
2861 mPrimaryDispSync.dump(result);
2862 dumpAll = false;
2863 }
Dan Stozab90cf072015-03-05 11:05:59 -08002864
2865 if ((index < numArgs) &&
2866 (args[index] == String16("--static-screen"))) {
2867 index++;
2868 dumpStaticScreenStats(result);
2869 dumpAll = false;
2870 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002871
2872 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002873 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002874 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002875 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002876 dumpAll = false;
2877 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002879
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002880 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002881 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002882 }
2883
Mathias Agopian9795c422009-08-26 16:36:26 -07002884 if (locked) {
2885 mStateLock.unlock();
2886 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
2888 write(fd, result.string(), result.size());
2889 return NO_ERROR;
2890}
2891
Dan Stozac7014012014-02-14 15:03:43 -08002892void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2893 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002894{
2895 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2896 const size_t count = currentLayers.size();
2897 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002898 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002899 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002900 }
2901}
2902
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002903void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002904 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002905{
2906 String8 name;
2907 if (index < args.size()) {
2908 name = String8(args[index]);
2909 index++;
2910 }
2911
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2913 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002914 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002915
2916 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002917 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002918 } else {
2919 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2920 const size_t count = currentLayers.size();
2921 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002922 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002923 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002924 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002925 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002926 }
2927 }
2928}
2929
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002930void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002931 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002932{
2933 String8 name;
2934 if (index < args.size()) {
2935 name = String8(args[index]);
2936 index++;
2937 }
2938
2939 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2940 const size_t count = currentLayers.size();
2941 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002942 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002943 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002944 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002945 }
2946 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002947
Svetoslavd85084b2014-03-20 10:28:31 -07002948 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002949}
2950
Jamie Gennis6547ff42013-07-16 20:12:42 -07002951// This should only be called from the main thread. Otherwise it would need
2952// the lock and should use mCurrentState rather than mDrawingState.
2953void SurfaceFlinger::logFrameStats() {
2954 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2955 const size_t count = drawingLayers.size();
2956 for (size_t i=0 ; i<count ; i++) {
2957 const sp<Layer>& layer(drawingLayers[i]);
2958 layer->logFrameStats();
2959 }
2960
2961 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2962}
2963
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002964void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07002965{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002966 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07002967#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002968 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07002969#endif
2970#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002971 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07002972#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002973 if (isLayerTripleBufferingDisabled())
2974 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002975 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07002976}
2977
Dan Stozab90cf072015-03-05 11:05:59 -08002978void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2979{
2980 result.appendFormat("Static screen stats:\n");
2981 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2982 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2983 float percent = 100.0f *
2984 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2985 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2986 b + 1, bucketTimeSec, percent);
2987 }
2988 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2989 float percent = 100.0f *
2990 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2991 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2992 NUM_BUCKETS - 1, bucketTimeSec, percent);
2993}
2994
Dan Stozae77c7662016-05-13 11:37:28 -07002995void SurfaceFlinger::recordBufferingStats(const char* layerName,
2996 std::vector<OccupancyTracker::Segment>&& history) {
2997 Mutex::Autolock lock(mBufferingStatsMutex);
2998 auto& stats = mBufferingStats[layerName];
2999 for (const auto& segment : history) {
3000 if (!segment.usedThirdBuffer) {
3001 stats.twoBufferTime += segment.totalTime;
3002 }
3003 if (segment.occupancyAverage < 1.0f) {
3004 stats.doubleBufferedTime += segment.totalTime;
3005 } else if (segment.occupancyAverage < 2.0f) {
3006 stats.tripleBufferedTime += segment.totalTime;
3007 }
3008 ++stats.numSegments;
3009 stats.totalTime += segment.totalTime;
3010 }
3011}
3012
Brian Andersond6927fb2016-07-23 23:37:30 -07003013void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3014 result.appendFormat("Layer frame timestamps:\n");
3015
3016 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3017 const size_t count = currentLayers.size();
3018 for (size_t i=0 ; i<count ; i++) {
3019 currentLayers[i]->dumpFrameEvents(result);
3020 }
3021}
3022
Dan Stozae77c7662016-05-13 11:37:28 -07003023void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3024 result.append("Buffering stats:\n");
3025 result.append(" [Layer name] <Active time> <Two buffer> "
3026 "<Double buffered> <Triple buffered>\n");
3027 Mutex::Autolock lock(mBufferingStatsMutex);
3028 typedef std::tuple<std::string, float, float, float> BufferTuple;
3029 std::map<float, BufferTuple, std::greater<float>> sorted;
3030 for (const auto& statsPair : mBufferingStats) {
3031 const char* name = statsPair.first.c_str();
3032 const BufferingStats& stats = statsPair.second;
3033 if (stats.numSegments == 0) {
3034 continue;
3035 }
3036 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3037 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3038 stats.totalTime;
3039 float doubleBufferRatio = static_cast<float>(
3040 stats.doubleBufferedTime) / stats.totalTime;
3041 float tripleBufferRatio = static_cast<float>(
3042 stats.tripleBufferedTime) / stats.totalTime;
3043 sorted.insert({activeTime, {name, twoBufferRatio,
3044 doubleBufferRatio, tripleBufferRatio}});
3045 }
3046 for (const auto& sortedPair : sorted) {
3047 float activeTime = sortedPair.first;
3048 const BufferTuple& values = sortedPair.second;
3049 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3050 std::get<0>(values).c_str(), activeTime,
3051 std::get<1>(values), std::get<2>(values),
3052 std::get<3>(values));
3053 }
3054 result.append("\n");
3055}
3056
3057
Mathias Agopian74d211a2013-04-22 16:55:35 +02003058void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3059 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003060{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003061 bool colorize = false;
3062 if (index < args.size()
3063 && (args[index] == String16("--color"))) {
3064 colorize = true;
3065 index++;
3066 }
3067
3068 Colorizer colorizer(colorize);
3069
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003070 // figure out if we're stuck somewhere
3071 const nsecs_t now = systemTime();
3072 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3073 const nsecs_t inTransaction(mDebugInTransaction);
3074 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3075 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3076
3077 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003078 * Dump library configuration.
3079 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003080
3081 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003082 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003083 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003084 appendSfConfigString(result);
3085 appendUiConfigString(result);
3086 appendGuiConfigString(result);
3087 result.append("\n");
3088
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003089 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003090 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003092 result.append(SyncFeatures::getInstance().toString());
3093 result.append("\n");
3094
Dan Stoza9e56aa02015-11-02 13:00:03 -08003095 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3096
Andy McFadden41d67d72014-04-25 16:58:34 -07003097 colorizer.bold(result);
3098 result.append("DispSync configuration: ");
3099 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003100 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3101 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003102 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3103 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003104 result.append("\n");
3105
Dan Stozab90cf072015-03-05 11:05:59 -08003106 // Dump static screen stats
3107 result.append("\n");
3108 dumpStaticScreenStats(result);
3109 result.append("\n");
3110
Dan Stozae77c7662016-05-13 11:37:28 -07003111 dumpBufferingStats(result);
3112
Andy McFadden4803b742012-09-24 19:07:20 -07003113 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003114 * Dump the visible layer list
3115 */
3116 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3117 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003118 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003119 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003120 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003121 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003122 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003123 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003124 }
3125
3126 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003127 * Dump Display state
3128 */
3129
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003130 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003131 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003132 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003133 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3134 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003135 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003136 }
3137
3138 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003139 * Dump SurfaceFlinger global state
3140 */
3141
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003142 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003143 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003144 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003145
Mathias Agopian888c8222012-08-04 21:10:38 -07003146 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003147 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003148
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003149 colorizer.bold(result);
3150 result.appendFormat("EGL implementation : %s\n",
3151 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3152 colorizer.reset(result);
3153 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003154 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003155
Mathias Agopian875d8e12013-06-07 15:35:48 -07003156 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003157
Mathias Agopian42977342012-08-05 00:40:46 -07003158 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003159 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3160 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003161 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003162 " last eglSwapBuffers() time: %f us\n"
3163 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003164 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003165 " refresh-rate : %f fps\n"
3166 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003167 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003168 " gpu_to_cpu_unsupported : %d\n"
3169 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170 mLastSwapBufferTime/1000.0,
3171 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003172 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003173 1e9 / activeConfig->getVsyncPeriod(),
3174 activeConfig->getDpiX(),
3175 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003176 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003177
Mathias Agopian74d211a2013-04-22 16:55:35 +02003178 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003179 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003180
Mathias Agopian74d211a2013-04-22 16:55:35 +02003181 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003182 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003183
3184 /*
3185 * VSYNC state
3186 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003187 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003188 result.append("\n");
3189
3190 /*
3191 * HWC layer minidump
3192 */
3193 for (size_t d = 0; d < mDisplays.size(); d++) {
3194 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3195 int32_t hwcId = displayDevice->getHwcDisplayId();
3196 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3197 continue;
3198 }
3199
3200 result.appendFormat("Display %d HWC layers:\n", hwcId);
3201 Layer::miniDumpHeader(result);
3202 for (size_t l = 0; l < count; l++) {
3203 const sp<Layer>& layer(currentLayers[l]);
3204 layer->miniDump(result, hwcId);
3205 }
3206 result.append("\n");
3207 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003208
3209 /*
3210 * Dump HWComposer state
3211 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003212 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003213 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003214 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003215 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003216 result.appendFormat(" h/w composer %s\n",
3217 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003218 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003219
3220 /*
3221 * Dump gralloc state
3222 */
3223 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3224 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003225}
3226
Mathias Agopian13127d82013-03-05 17:47:11 -08003227const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003228SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003229 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003230 wp<IBinder> dpy;
3231 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3232 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3233 dpy = mDisplays.keyAt(i);
3234 break;
3235 }
3236 }
3237 if (dpy == NULL) {
3238 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3239 // Just use the primary display so we have something to return
3240 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3241 }
3242 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003243}
3244
Keun young Park63f165f2012-08-31 10:53:36 -07003245bool SurfaceFlinger::startDdmConnection()
3246{
3247 void* libddmconnection_dso =
3248 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3249 if (!libddmconnection_dso) {
3250 return false;
3251 }
3252 void (*DdmConnection_start)(const char* name);
3253 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003254 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003255 if (!DdmConnection_start) {
3256 dlclose(libddmconnection_dso);
3257 return false;
3258 }
3259 (*DdmConnection_start)(getServiceName());
3260 return true;
3261}
3262
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003263status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003264 switch (code) {
3265 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003266 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003267 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003269 case CLEAR_ANIMATION_FRAME_STATS:
3270 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003271 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003272 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 {
3274 // codes that require permission check
3275 IPCThreadState* ipc = IPCThreadState::self();
3276 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003277 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003278 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003279 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003280 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003281 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003283 break;
3284 }
3285 case CAPTURE_SCREEN:
3286 {
3287 // codes that require permission check
3288 IPCThreadState* ipc = IPCThreadState::self();
3289 const int pid = ipc->getCallingPid();
3290 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003291 if ((uid != AID_GRAPHICS) &&
3292 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003293 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003294 return PERMISSION_DENIED;
3295 }
3296 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003297 }
3298 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003299 return OK;
3300}
3301
3302status_t SurfaceFlinger::onTransact(
3303 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3304{
3305 status_t credentialCheck = CheckTransactCodeCredentials(code);
3306 if (credentialCheck != OK) {
3307 return credentialCheck;
3308 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003310 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3311 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003312 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003313 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003314 IPCThreadState* ipc = IPCThreadState::self();
3315 const int pid = ipc->getCallingPid();
3316 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003317 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003318 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319 return PERMISSION_DENIED;
3320 }
3321 int n;
3322 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003323 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003324 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003325 return NO_ERROR;
3326 case 1002: // SHOW_UPDATES
3327 n = data.readInt32();
3328 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003329 invalidateHwcGeometry();
3330 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003332 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003333 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003334 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003336 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003337 setTransactionFlags(
3338 eTransactionNeeded|
3339 eDisplayTransactionNeeded|
3340 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003341 return NO_ERROR;
3342 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003343 case 1006:{ // send empty update
3344 signalRefresh();
3345 return NO_ERROR;
3346 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003347 case 1008: // toggle use of hw composer
3348 n = data.readInt32();
3349 mDebugDisableHWC = n ? 1 : 0;
3350 invalidateHwcGeometry();
3351 repaintEverything();
3352 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003353 case 1009: // toggle use of transform hint
3354 n = data.readInt32();
3355 mDebugDisableTransformHint = n ? 1 : 0;
3356 invalidateHwcGeometry();
3357 repaintEverything();
3358 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003360 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361 reply->writeInt32(0);
3362 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003363 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003364 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 return NO_ERROR;
3366 case 1013: {
3367 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003368 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3369 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003370 return NO_ERROR;
3371 }
3372 case 1014: {
3373 // daltonize
3374 n = data.readInt32();
3375 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003376 case 1:
3377 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3378 break;
3379 case 2:
3380 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3381 break;
3382 case 3:
3383 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3384 break;
3385 default:
3386 mDaltonizer.setType(ColorBlindnessType::None);
3387 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003388 }
3389 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003390 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003391 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003392 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003393 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003394 invalidateHwcGeometry();
3395 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003396 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003397 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003398 case 1015: {
3399 // apply a color matrix
3400 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003401 if (n) {
3402 // color matrix is sent as mat3 matrix followed by vec3
3403 // offset, then packed into a mat4 where the last row is
3404 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003405 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003406 for (size_t j = 0; j < 4; j++) {
3407 mColorMatrix[i][j] = data.readFloat();
3408 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003409 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003410 } else {
3411 mColorMatrix = mat4();
3412 }
3413 invalidateHwcGeometry();
3414 repaintEverything();
3415 return NO_ERROR;
3416 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003417 // This is an experimental interface
3418 // Needs to be shifted to proper binder interface when we productize
3419 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003420 n = data.readInt32();
3421 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003422 return NO_ERROR;
3423 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003424 case 1017: {
3425 n = data.readInt32();
3426 mForceFullDamage = static_cast<bool>(n);
3427 return NO_ERROR;
3428 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003429 case 1018: { // Modify Choreographer's phase offset
3430 n = data.readInt32();
3431 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3432 return NO_ERROR;
3433 }
3434 case 1019: { // Modify SurfaceFlinger's phase offset
3435 n = data.readInt32();
3436 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3437 return NO_ERROR;
3438 }
Irvel468051e2016-06-13 16:44:44 -07003439 case 1020: { // Layer updates interceptor
3440 n = data.readInt32();
3441 if (n) {
3442 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003443 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003444 }
3445 else{
3446 ALOGV("Interceptor disabled");
3447 mInterceptor.disable();
3448 }
3449 return NO_ERROR;
3450 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003451 case 1021: { // Disable HWC virtual displays
3452 n = data.readInt32();
3453 mUseHwcVirtualDisplays = !n;
3454 return NO_ERROR;
3455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456 }
3457 }
3458 return err;
3459}
3460
Mathias Agopian53331da2011-08-22 21:44:41 -07003461void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003462 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003463 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003464}
3465
Mathias Agopian59119e62010-10-11 12:37:43 -07003466// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003467// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003468// ---------------------------------------------------------------------------
3469
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003470/* The code below is here to handle b/8734824
3471 *
3472 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003473 * from the surfaceflinger thread to the calling binder thread, where they
3474 * are executed. This allows the calling thread in the calling process to be
3475 * reused and not depend on having "enough" binder threads to handle the
3476 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003477 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003478class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003479 /* Parts of GraphicProducerWrapper are run on two different threads,
3480 * communicating by sending messages via Looper but also by shared member
3481 * data. Coherence maintenance is subtle and in places implicit (ugh).
3482 *
3483 * Don't rely on Looper's sendMessage/handleMessage providing
3484 * release/acquire semantics for any data not actually in the Message.
3485 * Data going from surfaceflinger to binder threads needs to be
3486 * synchronized explicitly.
3487 *
3488 * Barrier open/wait do provide release/acquire semantics. This provides
3489 * implicit synchronization for data coming back from binder to
3490 * surfaceflinger threads.
3491 */
3492
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003493 sp<IGraphicBufferProducer> impl;
3494 sp<Looper> looper;
3495 status_t result;
3496 bool exitPending;
3497 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003498 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003499 uint32_t code;
3500 Parcel const* data;
3501 Parcel* reply;
3502
3503 enum {
3504 MSG_API_CALL,
3505 MSG_EXIT
3506 };
3507
3508 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003509 * Called on surfaceflinger thread. This is called by our "fake"
3510 * BpGraphicBufferProducer. We package the data and reply Parcel and
3511 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003512 */
3513 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003514 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003515 this->code = code;
3516 this->data = &data;
3517 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003518 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003519 // if we've exited, we run the message synchronously right here.
3520 // note (JH): as far as I can tell from looking at the code, this
3521 // never actually happens. if it does, i'm not sure if it happens
3522 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003523 handleMessage(Message(MSG_API_CALL));
3524 } else {
3525 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003526 // Prevent stores to this->{code, data, reply} from being
3527 // reordered later than the construction of Message.
3528 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003529 looper->sendMessage(this, Message(MSG_API_CALL));
3530 barrier.wait();
3531 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003532 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533 }
3534
3535 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003536 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003537 * call the real BpGraphicBufferProducer.
3538 */
3539 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003540 int what = message.what;
3541 // Prevent reads below from happening before the read from Message
3542 atomic_thread_fence(memory_order_acquire);
3543 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003544 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003545 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003546 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003547 exitRequested = true;
3548 }
3549 }
3550
3551public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003552 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003553 : impl(impl),
3554 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003555 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003556 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003557 exitRequested(false),
3558 code(0),
3559 data(NULL),
3560 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003561 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003562
Jesse Hallb154c422014-07-13 12:47:02 -07003563 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003564 status_t waitForResponse() {
3565 do {
3566 looper->pollOnce(-1);
3567 } while (!exitRequested);
3568 return result;
3569 }
3570
Jesse Hallb154c422014-07-13 12:47:02 -07003571 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003572 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003573 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003574 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003575 // Ensure this->result is visible to the binder thread before it
3576 // handles the message.
3577 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003578 looper->sendMessage(this, Message(MSG_EXIT));
3579 }
3580};
3581
3582
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003583status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3584 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003585 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003586 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003587 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003588
3589 if (CC_UNLIKELY(display == 0))
3590 return BAD_VALUE;
3591
3592 if (CC_UNLIKELY(producer == 0))
3593 return BAD_VALUE;
3594
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003595 // if we have secure windows on this display, never allow the screen capture
3596 // unless the producer interface is local (i.e.: we can take a screenshot for
3597 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003598 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003599
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003600 // Convert to surfaceflinger's internal rotation type.
3601 Transform::orientation_flags rotationFlags;
3602 switch (rotation) {
3603 case ISurfaceComposer::eRotateNone:
3604 rotationFlags = Transform::ROT_0;
3605 break;
3606 case ISurfaceComposer::eRotate90:
3607 rotationFlags = Transform::ROT_90;
3608 break;
3609 case ISurfaceComposer::eRotate180:
3610 rotationFlags = Transform::ROT_180;
3611 break;
3612 case ISurfaceComposer::eRotate270:
3613 rotationFlags = Transform::ROT_270;
3614 break;
3615 default:
3616 rotationFlags = Transform::ROT_0;
3617 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3618 break;
3619 }
3620
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003621 class MessageCaptureScreen : public MessageBase {
3622 SurfaceFlinger* flinger;
3623 sp<IBinder> display;
3624 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003625 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003626 uint32_t reqWidth, reqHeight;
3627 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003628 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003629 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003630 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003631 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003632 public:
3633 MessageCaptureScreen(SurfaceFlinger* flinger,
3634 const sp<IBinder>& display,
3635 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003636 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003637 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003638 bool useIdentityTransform,
3639 Transform::orientation_flags rotation,
3640 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003641 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003642 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003643 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003644 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003645 rotation(rotation), result(PERMISSION_DENIED),
3646 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003647 {
3648 }
3649 status_t getResult() const {
3650 return result;
3651 }
3652 virtual bool handler() {
3653 Mutex::Autolock _l(flinger->mStateLock);
3654 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003655 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003656 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003657 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003658 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003659 return true;
3660 }
3661 };
3662
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003663 // this creates a "fake" BBinder which will serve as a "fake" remote
3664 // binder to receive the marshaled calls and forward them to the
3665 // real remote (a BpGraphicBufferProducer)
3666 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3667
3668 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3669 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003670 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003671 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003672 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003673 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003674
3675 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003676 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003677 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003678 }
3679 return res;
3680}
3681
Mathias Agopian180f10d2013-04-10 22:55:41 -07003682
3683void SurfaceFlinger::renderScreenImplLocked(
3684 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003685 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003686 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003687 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003688{
3689 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003690 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003691
3692 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003693 const int32_t hw_w = hw->getWidth();
3694 const int32_t hw_h = hw->getHeight();
3695 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003696 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003697
Dan Stozac1879002014-05-22 15:59:05 -07003698 // if a default or invalid sourceCrop is passed in, set reasonable values
3699 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3700 !sourceCrop.isValid()) {
3701 sourceCrop.setLeftTop(Point(0, 0));
3702 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3703 }
3704
3705 // ensure that sourceCrop is inside screen
3706 if (sourceCrop.left < 0) {
3707 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3708 }
Dan Stozabe31f442014-06-11 11:20:54 -07003709 if (sourceCrop.right > hw_w) {
3710 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003711 }
3712 if (sourceCrop.top < 0) {
3713 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3714 }
Dan Stozabe31f442014-06-11 11:20:54 -07003715 if (sourceCrop.bottom > hw_h) {
3716 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003717 }
3718
Mathias Agopian180f10d2013-04-10 22:55:41 -07003719 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003720 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003721
3722 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003723 engine.setViewportAndProjection(
3724 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003725 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003726
3727 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003728 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003729
3730 const LayerVector& layers( mDrawingState.layersSortedByZ );
3731 const size_t count = layers.size();
3732 for (size_t i=0 ; i<count ; ++i) {
3733 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003734 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003735 if (state.layerStack == hw->getLayerStack()) {
3736 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3737 if (layer->isVisible()) {
3738 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003739 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003740 if (filtering) layer->setFiltering(false);
3741 }
3742 }
3743 }
3744 }
3745
Mathias Agopian931bda12013-08-28 18:11:46 -07003746 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003747}
3748
3749
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003750status_t SurfaceFlinger::captureScreenImplLocked(
3751 const sp<const DisplayDevice>& hw,
3752 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003753 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003754 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003755 bool useIdentityTransform, Transform::orientation_flags rotation,
3756 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003757{
3758 ATRACE_CALL();
3759
Mathias Agopian180f10d2013-04-10 22:55:41 -07003760 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003761 uint32_t hw_w = hw->getWidth();
3762 uint32_t hw_h = hw->getHeight();
3763
3764 if (rotation & Transform::ROT_90) {
3765 std::swap(hw_w, hw_h);
3766 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003767
Mathias Agopian180f10d2013-04-10 22:55:41 -07003768 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3769 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3770 reqWidth, reqHeight, hw_w, hw_h);
3771 return BAD_VALUE;
3772 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003773
Mathias Agopian180f10d2013-04-10 22:55:41 -07003774 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3775 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3776
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003777 bool secureLayerIsVisible = false;
3778 const LayerVector& layers(mDrawingState.layersSortedByZ);
3779 const size_t count = layers.size();
3780 for (size_t i = 0 ; i < count ; ++i) {
3781 const sp<Layer>& layer(layers[i]);
3782 const Layer::State& state(layer->getDrawingState());
3783 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3784 state.z <= maxLayerZ && layer->isVisible() &&
3785 layer->isSecure()) {
3786 secureLayerIsVisible = true;
3787 }
3788 }
3789
3790 if (!isLocalScreenshot && secureLayerIsVisible) {
3791 ALOGW("FB is protected: PERMISSION_DENIED");
3792 return PERMISSION_DENIED;
3793 }
3794
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003795 // create a surface (because we're a producer, and we need to
3796 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003797 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003798
3799 // Put the screenshot Surface into async mode so that
3800 // Layer::headFenceHasSignaled will always return true and we'll latch the
3801 // first buffer regardless of whether or not its acquire fence has
3802 // signaled. This is needed to avoid a race condition in the rotation
3803 // animation. See b/30209608
3804 sur->setAsyncMode(true);
3805
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003806 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003807
Michael Lentine5a16a622015-05-21 13:48:24 -07003808 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3809 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003810 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3811 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003812
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003813 int err = 0;
3814 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003815 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003816 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3817 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003818
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003819 if (err == NO_ERROR) {
3820 ANativeWindowBuffer* buffer;
3821 /* TODO: Once we have the sync framework everywhere this can use
3822 * server-side waits on the fence that dequeueBuffer returns.
3823 */
3824 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3825 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003826 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003827 // create an EGLImage from the buffer so we can later
3828 // turn it into a texture
3829 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3830 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3831 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003832 // this binds the given EGLImage as a framebuffer for the
3833 // duration of this scope.
3834 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3835 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003836 // this will in fact render into our dequeued buffer
3837 // via an FBO, which means we didn't have to create
3838 // an EGLSurface and therefore we're not
3839 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003840 renderScreenImplLocked(
3841 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3842 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003843
Riley Andrews86639902014-08-15 12:27:24 -07003844 // Attempt to create a sync khr object that can produce a sync point. If that
3845 // isn't available, create a non-dupable sync object in the fallback path and
3846 // wait on it directly.
3847 EGLSyncKHR sync;
3848 if (!DEBUG_SCREENSHOTS) {
3849 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003850 // native fence fd will not be populated until flush() is done.
3851 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003852 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003853 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003854 }
Riley Andrews86639902014-08-15 12:27:24 -07003855 if (sync != EGL_NO_SYNC_KHR) {
3856 // get the sync fd
3857 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3858 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3859 ALOGW("captureScreen: failed to dup sync khr object");
3860 syncFd = -1;
3861 }
3862 eglDestroySyncKHR(mEGLDisplay, sync);
3863 } else {
3864 // fallback path
3865 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3866 if (sync != EGL_NO_SYNC_KHR) {
3867 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3868 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3869 EGLint eglErr = eglGetError();
3870 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3871 ALOGW("captureScreen: fence wait timed out");
3872 } else {
3873 ALOGW_IF(eglErr != EGL_SUCCESS,
3874 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3875 }
3876 eglDestroySyncKHR(mEGLDisplay, sync);
3877 } else {
3878 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3879 }
3880 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003881 if (DEBUG_SCREENSHOTS) {
3882 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3883 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3884 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3885 hw, minLayerZ, maxLayerZ);
3886 delete [] pixels;
3887 }
3888
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003889 } else {
3890 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3891 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003892 window->cancelBuffer(window, buffer, syncFd);
3893 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003894 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003895 // destroy our image
3896 eglDestroyImageKHR(mEGLDisplay, image);
3897 } else {
3898 result = BAD_VALUE;
3899 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003900 if (buffer) {
3901 // queueBuffer takes ownership of syncFd
3902 result = window->queueBuffer(window, buffer, syncFd);
3903 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003904 }
3905 } else {
3906 result = BAD_VALUE;
3907 }
3908 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3909 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003910
Mathias Agopian74c40c02010-09-29 13:02:36 -07003911 return result;
3912}
3913
Mathias Agopiand5556842013-09-19 17:08:37 -07003914void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003915 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003916 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003917 for (size_t y=0 ; y<h ; y++) {
3918 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3919 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003920 if (p[x] != 0xFF000000) return;
3921 }
3922 }
3923 ALOGE("*** we just took a black screenshot ***\n"
3924 "requested minz=%d, maxz=%d, layerStack=%d",
3925 minLayerZ, maxLayerZ, hw->getLayerStack());
3926 const LayerVector& layers( mDrawingState.layersSortedByZ );
3927 const size_t count = layers.size();
3928 for (size_t i=0 ; i<count ; ++i) {
3929 const sp<Layer>& layer(layers[i]);
3930 const Layer::State& state(layer->getDrawingState());
3931 const bool visible = (state.layerStack == hw->getLayerStack())
3932 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3933 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003934 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003935 visible ? '+' : '-',
3936 i, layer->getName().string(), state.layerStack, state.z,
3937 layer->isVisible(), state.flags, state.alpha);
3938 }
3939 }
3940}
3941
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003942// ---------------------------------------------------------------------------
3943
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003944SurfaceFlinger::LayerVector::LayerVector() {
3945}
3946
3947SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003948 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003949}
3950
3951int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3952 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003953{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003954 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003955 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3956 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003957
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003958 uint32_t ls = l->getCurrentState().layerStack;
3959 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003960 if (ls != rs)
3961 return ls - rs;
3962
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003963 uint32_t lz = l->getCurrentState().z;
3964 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003965 if (lz != rz)
3966 return lz - rz;
3967
3968 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003969}
3970
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003971}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003972
3973
3974#if defined(__gl_h_)
3975#error "don't include gl/gl.h in this file"
3976#endif
3977
3978#if defined(__gl2_h_)
3979#error "don't include gl2/gl2.h in this file"
3980#endif