blob: 3e30ebda6e37e2f4d3c24416312bc72281b64b8f [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 Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.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"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800118uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800119bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800120bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800121int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600122bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700125 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700127 mTransactionPending(false),
128 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700129 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700130 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700131 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800132 mHwc(nullptr),
133 mRealHwc(nullptr),
134 mVrHwc(nullptr),
135 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800140 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700142 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700143 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700144 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700145 mDebugInSwapBuffers(0),
146 mLastSwapBufferTime(0),
147 mDebugInTransaction(0),
148 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700149 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700150 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800151 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasColorMatrix(false),
156 mHasPoweredOff(false),
157 mFrameBuckets(),
158 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700159 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800160 mNumLayers(0),
161 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800163 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800164
165 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
166 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
167
168 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
169 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
170
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800171 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
172 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700174 useContextPriority = getBool< ISurfaceFlingerConfigs,
175 &ISurfaceFlingerConfigs::useContextPriority>(false);
176
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700177 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
178 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
179
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700180 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
181 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
182
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800183 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
184 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
185
Steven Thomas050b2c82017-03-06 11:45:16 -0800186 // Vr flinger is only enabled on Daydream ready devices.
187 useVrFlinger = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::useVrFlinger>(false);
189
Fabien Sanglard1971b632017-03-10 14:50:03 -0800190 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
192
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600193 hasWideColorDisplay =
194 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 // debugging stuff...
197 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700198
Mathias Agopianb4b17302013-03-20 18:36:41 -0700199 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700200 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 property_get("debug.sf.showupdates", value, "0");
203 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205 property_get("debug.sf.ddms", value, "0");
206 mDebugDDMS = atoi(value);
207 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700208 if (!startDdmConnection()) {
209 // start failed, and DDMS debugging not enabled
210 mDebugDDMS = 0;
211 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700212 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700213 ALOGI_IF(mDebugRegion, "showupdates enabled");
214 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700215
216 property_get("debug.sf.disable_backpressure", value, "0");
217 mPropagateBackpressure = !atoi(value);
218 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700219
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800220 property_get("debug.sf.enable_hwc_vds", value, "0");
221 mUseHwcVirtualDisplays = atoi(value);
222 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800223
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800224 property_get("ro.sf.disable_triple_buffer", value, "1");
225 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800226 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227}
228
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229void SurfaceFlinger::onFirstRef()
230{
231 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800232}
233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234SurfaceFlinger::~SurfaceFlinger()
235{
Mathias Agopiana4912602012-07-12 14:25:33 -0700236 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
237 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
238 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239}
240
Dan Stozac7014012014-02-14 15:03:43 -0800241void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242{
243 // the window manager died on us. prepare its eulogy.
244
Andy McFadden13a082e2012-08-24 10:16:42 -0700245 // restore initial conditions (default device unblank, etc)
246 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247
248 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700249 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250}
251
Robert Carr1db73f62016-12-21 12:58:51 -0800252static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700253 status_t err = client->initCheck();
254 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return nullptr;
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
261 return initClient(new Client(this));
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
265 const sp<IGraphicBufferProducer>& gbp) {
266 if (authenticateSurfaceTexture(gbp) == false) {
267 return nullptr;
268 }
269 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
270 if (layer == nullptr) {
271 return nullptr;
272 }
273
274 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700277sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
278 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279{
280 class DisplayToken : public BBinder {
281 sp<SurfaceFlinger> flinger;
282 virtual ~DisplayToken() {
283 // no more references, this display must be terminated
284 Mutex::Autolock _l(flinger->mStateLock);
285 flinger->mCurrentState.displays.removeItem(this);
286 flinger->setTransactionFlags(eDisplayTransactionNeeded);
287 }
288 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700289 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 : flinger(flinger) {
291 }
292 };
293
294 sp<BBinder> token = new DisplayToken(this);
295
296 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700297 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700298 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 return token;
302}
303
Jesse Hall6c913be2013-08-08 12:15:49 -0700304void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
305 Mutex::Autolock _l(mStateLock);
306
307 ssize_t idx = mCurrentState.displays.indexOfKey(display);
308 if (idx < 0) {
309 ALOGW("destroyDisplay: invalid display token");
310 return;
311 }
312
313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
314 if (!info.isVirtualDisplay()) {
315 ALOGE("destroyDisplay called for non-virtual display");
316 return;
317 }
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700319 mCurrentState.displays.removeItemsAt(idx);
320 setTransactionFlags(eDisplayTransactionNeeded);
321}
322
Jesse Hall692c7232012-11-08 15:41:56 -0800323void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800324 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 ALOGW_IF(mBuiltinDisplays[type],
326 "Overwriting display token for display type %d", type);
327 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800328 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700329 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700331 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800332}
333
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700335 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
337 return NULL;
338 }
Jesse Hall692c7232012-11-08 15:41:56 -0800339 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340}
341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342void SurfaceFlinger::bootFinished()
343{
Wei Wangb254fa32017-01-31 17:43:23 -0800344 if (mStartBootAnimThread->join() != NO_ERROR) {
345 ALOGE("Join StartBootAnimThread failed!");
346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 const nsecs_t now = systemTime();
348 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000349 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700350 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700351
352 // wait patiently for the window manager death
353 const String16 name("window");
354 sp<IBinder> window(defaultServiceManager()->getService(name));
355 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700356 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357 }
358
Steven Thomas050b2c82017-03-06 11:45:16 -0800359 if (mVrFlinger) {
360 mVrFlinger->OnBootFinished();
361 }
362
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 // formerly we would just kill the process, but we now ask it to exit so it
365 // can choose where to stop the animation.
366 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700367
368 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
369 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
370 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371}
372
Mathias Agopian3f844832013-08-07 21:24:32 -0700373void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700374 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 RenderEngine& engine;
376 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700377 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
379 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380 }
381 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383 return true;
384 }
385 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387}
388
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389class DispSyncSource : public VSyncSource, private DispSync::Callback {
390public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700391 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000392 const char* name) :
393 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700394 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700395 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000396 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
397 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 mDispSync(dispSync),
399 mCallbackMutex(),
400 mCallback(),
401 mVsyncMutex(),
402 mPhaseOffset(phaseOffset),
403 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700404
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700405 virtual ~DispSyncSource() {}
406
407 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700408 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000410 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700411 static_cast<DispSync::Callback*>(this));
412 if (err != NO_ERROR) {
413 ALOGE("error registering vsync callback: %s (%d)",
414 strerror(-err), err);
415 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700416 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 } else {
418 status_t err = mDispSync->removeEventListener(
419 static_cast<DispSync::Callback*>(this));
420 if (err != NO_ERROR) {
421 ALOGE("error unregistering vsync callback: %s (%d)",
422 strerror(-err), err);
423 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700424 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700426 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 }
428
429 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 mCallback = callback;
432 }
433
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 virtual void setPhaseOffset(nsecs_t phaseOffset) {
435 Mutex::Autolock lock(mVsyncMutex);
436
437 // Normalize phaseOffset to [0, period)
438 auto period = mDispSync->getPeriod();
439 phaseOffset %= period;
440 if (phaseOffset < 0) {
441 // If we're here, then phaseOffset is in (-period, 0). After this
442 // operation, it will be in (0, period)
443 phaseOffset += period;
444 }
445 mPhaseOffset = phaseOffset;
446
447 // If we're not enabled, we don't need to mess with the listeners
448 if (!mEnabled) {
449 return;
450 }
451
452 // Remove the listener with the old offset
453 status_t err = mDispSync->removeEventListener(
454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error unregistering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
459
460 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000461 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error registering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
467 }
468
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469private:
470 virtual void onDispSyncEvent(nsecs_t when) {
471 sp<VSyncSource::Callback> callback;
472 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 callback = mCallback;
475
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700476 if (mTraceVsync) {
477 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700478 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700479 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 if (callback != NULL) {
483 callback->onVSyncEvent(when);
484 }
485 }
486
Tim Murray4a4e4a22016-04-19 16:29:23 +0000487 const char* const mName;
488
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 int mValue;
490
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700492 const String8 mVsyncOnLabel;
493 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700494
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496
497 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499
500 Mutex mVsyncMutex; // Protects the following
501 nsecs_t mPhaseOffset;
502 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503};
504
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700505class InjectVSyncSource : public VSyncSource {
506public:
507 InjectVSyncSource() {}
508
509 virtual ~InjectVSyncSource() {}
510
511 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
512 std::lock_guard<std::mutex> lock(mCallbackMutex);
513 mCallback = callback;
514 }
515
516 virtual void onInjectSyncEvent(nsecs_t when) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback->onVSyncEvent(when);
519 }
520
521 virtual void setVSyncEnabled(bool) {}
522 virtual void setPhaseOffset(nsecs_t) {}
523
524private:
525 std::mutex mCallbackMutex; // Protects the following
526 sp<VSyncSource::Callback> mCallback;
527};
528
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700530 ALOGI( "SurfaceFlinger's main thread ready to run. "
531 "Initializing graphics H/W...");
532
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900533 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
534
Dan Stoza9e56aa02015-11-02 13:00:03 -0800535 { // Autolock scope
536 Mutex::Autolock _l(mStateLock);
537
538 // initialize EGL for the default display
539 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
540 eglInitialize(mEGLDisplay, NULL, NULL);
541
542 // start the EventThread
543 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
544 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700545 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800546 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
547 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700548 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 mEventQueue.setEventThread(mSFEventThread);
550
Tim Murray22752852017-05-04 13:38:49 -0700551 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700552 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700553 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700554 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
555 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
556 }
Tim Murray22752852017-05-04 13:38:49 -0700557 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
558 ALOGE("Couldn't set SCHED_FIFO for EventThread");
559 }
Tim Murray41a38532016-06-22 12:42:10 -0700560
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 // Get a RenderEngine for the given display / config (can't fail)
562 mRenderEngine = RenderEngine::create(mEGLDisplay,
563 HAL_PIXEL_FORMAT_RGBA_8888);
564 }
565
566 // Drop the state lock while we initialize the hardware composer. We drop
567 // the lock because on creation, it will call back into SurfaceFlinger to
568 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800569 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
570 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800571 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800572 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
574
Jesse Hall692c7232012-11-08 15:41:56 -0800575 Mutex::Autolock _l(mStateLock);
576
Ian Elliott5c34de22017-04-10 14:42:30 -0600577 // Inform native graphics APIs whether the present timestamp is supported:
578 if (getHwComposer().hasCapability(
579 HWC2::Capability::PresentFenceIsNotReliable)) {
580 property_set(kTimestampProperty, "0");
581 } else {
582 property_set(kTimestampProperty, "1");
583 }
584
Steven Thomas050b2c82017-03-06 11:45:16 -0800585 if (useVrFlinger) {
586 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
587 mVrFlingerRequestsDisplay = requestDisplay;
588 signalTransaction();
589 };
590 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
591 vrFlingerRequestDisplayCallback);
592 if (!mVrFlinger) {
593 ALOGE("Failed to start vrflinger");
594 }
595 }
596
Mathias Agopian875d8e12013-06-07 15:35:48 -0700597 // retrieve the EGL context that was selected/created
598 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700599
Mathias Agopianda27af92012-09-13 18:17:13 -0700600 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
601 "couldn't create EGLContext");
602
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603 // make the GLContext current so that we can create textures when creating
604 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700605 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700606
Jamie Gennisd1700752013-10-14 12:22:52 -0700607 mEventControlThread = new EventControlThread(this);
608 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
609
Mathias Agopian92a979a2012-08-02 18:32:23 -0700610 // initialize our drawing state
611 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700612
Andy McFadden13a082e2012-08-24 10:16:42 -0700613 // set initial conditions (e.g. unblank default device)
614 initializeDisplays();
615
Dan Stoza4e637772016-07-28 13:31:51 -0700616 mRenderEngine->primeCache();
617
Wei Wangb254fa32017-01-31 17:43:23 -0800618 mStartBootAnimThread = new StartBootAnimThread();
619 if (mStartBootAnimThread->Start() != NO_ERROR) {
620 ALOGE("Run StartBootAnimThread failed!");
621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800622
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700624}
625
Mathias Agopiana67e4182012-06-19 17:26:12 -0700626void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800627 // Start boot animation service by setting a property mailbox
628 // if property setting thread is already running, Start() will be just a NOP
629 mStartBootAnimThread->Start();
630 // Wait until property was set
631 if (mStartBootAnimThread->join() != NO_ERROR) {
632 ALOGE("Join StartBootAnimThread failed!");
633 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700634}
635
Mathias Agopian875d8e12013-06-07 15:35:48 -0700636size_t SurfaceFlinger::getMaxTextureSize() const {
637 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700638}
639
Mathias Agopian875d8e12013-06-07 15:35:48 -0700640size_t SurfaceFlinger::getMaxViewportDims() const {
641 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700642}
643
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800644// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800645
Jamie Gennis582270d2011-08-17 18:19:00 -0700646bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800647 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800648 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800649 return authenticateSurfaceTextureLocked(bufferProducer);
650}
651
652bool SurfaceFlinger::authenticateSurfaceTextureLocked(
653 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800654 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700655 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800656}
657
Brian Anderson6b376712017-04-04 10:51:39 -0700658status_t SurfaceFlinger::getSupportedFrameTimestamps(
659 std::vector<FrameEvent>* outSupported) const {
660 *outSupported = {
661 FrameEvent::REQUESTED_PRESENT,
662 FrameEvent::ACQUIRE,
663 FrameEvent::LATCH,
664 FrameEvent::FIRST_REFRESH_START,
665 FrameEvent::LAST_REFRESH_START,
666 FrameEvent::GPU_COMPOSITION_DONE,
667 FrameEvent::DEQUEUE_READY,
668 FrameEvent::RELEASE,
669 };
670 if (!getHwComposer().hasCapability(
671 HWC2::Capability::PresentFenceIsNotReliable)) {
672 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
673 }
674 return NO_ERROR;
675}
676
Dan Stoza7f7da322014-05-02 15:26:25 -0700677status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
678 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700679 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700680 return BAD_VALUE;
681 }
682
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500683 if (!display.get())
684 return NAME_NOT_FOUND;
685
Jesse Hall692c7232012-11-08 15:41:56 -0800686 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700687 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800688 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700689 type = i;
690 break;
691 }
692 }
693
694 if (type < 0) {
695 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700696 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700697
Mathias Agopian8b736f12012-08-13 17:54:26 -0700698 // TODO: Not sure if display density should handled by SF any longer
699 class Density {
700 static int getDensityFromProperty(char const* propName) {
701 char property[PROPERTY_VALUE_MAX];
702 int density = 0;
703 if (property_get(propName, property, NULL) > 0) {
704 density = atoi(property);
705 }
706 return density;
707 }
708 public:
709 static int getEmuDensity() {
710 return getDensityFromProperty("qemu.sf.lcd_density"); }
711 static int getBuildDensity() {
712 return getDensityFromProperty("ro.sf.lcd_density"); }
713 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700714
Dan Stoza7f7da322014-05-02 15:26:25 -0700715 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700716
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700718 DisplayInfo info = DisplayInfo();
719
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720 float xdpi = hwConfig->getDpiX();
721 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700722
723 if (type == DisplayDevice::DISPLAY_PRIMARY) {
724 // The density of the device is provided by a build property
725 float density = Density::getBuildDensity() / 160.0f;
726 if (density == 0) {
727 // the build doesn't provide a density -- this is wrong!
728 // use xdpi instead
729 ALOGE("ro.sf.lcd_density must be defined as a build property");
730 density = xdpi / 160.0f;
731 }
732 if (Density::getEmuDensity()) {
733 // if "qemu.sf.lcd_density" is specified, it overrides everything
734 xdpi = ydpi = density = Density::getEmuDensity();
735 density /= 160.0f;
736 }
737 info.density = density;
738
739 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000740 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
741 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700742 } else {
743 // TODO: where should this value come from?
744 static const int TV_DENSITY = 213;
745 info.density = TV_DENSITY / 160.0f;
746 info.orientation = 0;
747 }
748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 info.w = hwConfig->getWidth();
750 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 info.xdpi = xdpi;
752 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900754 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755
Andy McFadden91b2ca82014-06-13 14:04:23 -0700756 // This is how far in advance a buffer must be queued for
757 // presentation at a given time. If you want a buffer to appear
758 // on the screen at time N, you must submit the buffer before
759 // (N - presentationDeadline).
760 //
761 // Normally it's one full refresh period (to give SF a chance to
762 // latch the buffer), but this can be reduced by configuring a
763 // DispSync offset. Any additional delays introduced by the hardware
764 // composer or panel must be accounted for here.
765 //
766 // We add an additional 1ms to allow for processing time and
767 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800768 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800769 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700770
771 // All non-virtual displays are currently considered secure.
772 info.secure = true;
773
Michael Wright28f24d02016-07-12 13:30:53 -0700774 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700775 }
776
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 return NO_ERROR;
778}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700779
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800780status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700781 DisplayStatInfo* stats) {
782 if (stats == NULL) {
783 return BAD_VALUE;
784 }
785
786 // FIXME for now we always return stats for the primary display
787 memset(stats, 0, sizeof(*stats));
788 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
789 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
790 return NO_ERROR;
791}
792
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700793int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800794 if (display == NULL) {
795 ALOGE("%s : display is NULL", __func__);
796 return BAD_VALUE;
797 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700798
799 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700800 if (device != NULL) {
801 return device->getActiveConfig();
802 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700803
Dan Stoza24a42e92015-03-09 10:04:11 -0700804 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700805}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700806
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700807void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
808 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
809 this);
810 int32_t type = hw->getDisplayType();
811 int currentMode = hw->getActiveConfig();
812
813 if (mode == currentMode) {
814 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
815 return;
816 }
817
818 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
819 ALOGW("Trying to set config for virtual display");
820 return;
821 }
822
823 hw->setActiveConfig(mode);
824 getHwComposer().setActiveConfig(type, mode);
825}
826
827status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
828 class MessageSetActiveConfig: public MessageBase {
829 SurfaceFlinger& mFlinger;
830 sp<IBinder> mDisplay;
831 int mMode;
832 public:
833 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
834 int mode) :
835 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
836 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700837 Vector<DisplayInfo> configs;
838 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700839 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700840 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700841 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700842 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700843 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700844 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
845 if (hw == NULL) {
846 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700847 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700848 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
849 ALOGW("Attempt to set active config = %d for virtual display",
850 mMode);
851 } else {
852 mFlinger.setActiveConfigInternal(hw, mMode);
853 }
854 return true;
855 }
856 };
857 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
858 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700859 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700860}
Michael Wright28f24d02016-07-12 13:30:53 -0700861status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
862 Vector<android_color_mode_t>* outColorModes) {
863 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
864 return BAD_VALUE;
865 }
866
867 if (!display.get()) {
868 return NAME_NOT_FOUND;
869 }
870
871 int32_t type = NAME_NOT_FOUND;
872 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
873 if (display == mBuiltinDisplays[i]) {
874 type = i;
875 break;
876 }
877 }
878
879 if (type < 0) {
880 return type;
881 }
882
883 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
884 outColorModes->clear();
885 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
886
887 return NO_ERROR;
888}
889
890android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700891 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700892 if (device != nullptr) {
893 return device->getActiveColorMode();
894 }
895 return static_cast<android_color_mode_t>(BAD_VALUE);
896}
897
898void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
899 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700900 int32_t type = hw->getDisplayType();
901 android_color_mode_t currentMode = hw->getActiveColorMode();
902
903 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700904 return;
905 }
906
907 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
908 ALOGW("Trying to set config for virtual display");
909 return;
910 }
911
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600912 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
913 hw->getDisplayType());
914
Michael Wright28f24d02016-07-12 13:30:53 -0700915 hw->setActiveColorMode(mode);
916 getHwComposer().setActiveColorMode(type, mode);
917}
918
919
920status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
921 android_color_mode_t colorMode) {
922 class MessageSetActiveColorMode: public MessageBase {
923 SurfaceFlinger& mFlinger;
924 sp<IBinder> mDisplay;
925 android_color_mode_t mMode;
926 public:
927 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
928 android_color_mode_t mode) :
929 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
930 virtual bool handler() {
931 Vector<android_color_mode_t> modes;
932 mFlinger.getDisplayColorModes(mDisplay, &modes);
933 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
934 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600935 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
936 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700937 return true;
938 }
939 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
940 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600941 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
942 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700943 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600944 ALOGW("Attempt to set active color mode %s %d for virtual display",
945 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700946 } else {
947 mFlinger.setActiveColorModeInternal(hw, mMode);
948 }
949 return true;
950 }
951 };
952 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
953 postMessageSync(msg);
954 return NO_ERROR;
955}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700956
Svetoslavd85084b2014-03-20 10:28:31 -0700957status_t SurfaceFlinger::clearAnimationFrameStats() {
958 Mutex::Autolock _l(mStateLock);
959 mAnimFrameTracker.clearStats();
960 return NO_ERROR;
961}
962
963status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
964 Mutex::Autolock _l(mStateLock);
965 mAnimFrameTracker.getStats(outStats);
966 return NO_ERROR;
967}
968
Dan Stozac4f471e2016-03-24 09:31:08 -0700969status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
970 HdrCapabilities* outCapabilities) const {
971 Mutex::Autolock _l(mStateLock);
972
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700973 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700974 if (displayDevice == nullptr) {
975 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
976 return BAD_VALUE;
977 }
978
979 std::unique_ptr<HdrCapabilities> capabilities =
980 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
981 if (capabilities) {
982 std::swap(*outCapabilities, *capabilities);
983 } else {
984 return BAD_VALUE;
985 }
986
987 return NO_ERROR;
988}
989
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700990status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
991 if (enable == mInjectVSyncs) {
992 return NO_ERROR;
993 }
994
995 if (enable) {
996 mInjectVSyncs = enable;
997 ALOGV("VSync Injections enabled");
998 if (mVSyncInjector.get() == nullptr) {
999 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001000 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001001 }
1002 mEventQueue.setEventThread(mInjectorEventThread);
1003 } else {
1004 mInjectVSyncs = enable;
1005 ALOGV("VSync Injections disabled");
1006 mEventQueue.setEventThread(mSFEventThread);
1007 mVSyncInjector.clear();
1008 }
1009 return NO_ERROR;
1010}
1011
1012status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1013 if (!mInjectVSyncs) {
1014 ALOGE("VSync Injections not enabled");
1015 return BAD_VALUE;
1016 }
1017 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1018 ALOGV("Injecting VSync inside SurfaceFlinger");
1019 mVSyncInjector->onInjectSyncEvent(when);
1020 }
1021 return NO_ERROR;
1022}
1023
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001024// ----------------------------------------------------------------------------
1025
1026sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001027 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001028}
1029
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001030// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001031
1032void SurfaceFlinger::waitForEvent() {
1033 mEventQueue.waitMessage();
1034}
1035
1036void SurfaceFlinger::signalTransaction() {
1037 mEventQueue.invalidate();
1038}
1039
1040void SurfaceFlinger::signalLayerUpdate() {
1041 mEventQueue.invalidate();
1042}
1043
1044void SurfaceFlinger::signalRefresh() {
1045 mEventQueue.refresh();
1046}
1047
1048status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001049 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001050 return mEventQueue.postMessage(msg, reltime);
1051}
1052
1053status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001054 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001055 status_t res = mEventQueue.postMessage(msg, reltime);
1056 if (res == NO_ERROR) {
1057 msg->wait();
1058 }
1059 return res;
1060}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001061
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001062void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001063 do {
1064 waitForEvent();
1065 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001066}
1067
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001068void SurfaceFlinger::enableHardwareVsync() {
1069 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001070 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001072 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1073 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001075 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076}
1077
Jesse Hall948fe0c2013-10-14 12:56:09 -07001078void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079 Mutex::Autolock _l(mHWVsyncLock);
1080
Jesse Hall948fe0c2013-10-14 12:56:09 -07001081 if (makeAvailable) {
1082 mHWVsyncAvailable = true;
1083 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001084 // Hardware vsync is not currently available, so abort the resync
1085 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001086 return;
1087 }
1088
Dan Stoza9e56aa02015-11-02 13:00:03 -08001089 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1090 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001091
1092 mPrimaryDispSync.reset();
1093 mPrimaryDispSync.setPeriod(period);
1094
1095 if (!mPrimaryHWVsyncEnabled) {
1096 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001097 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1098 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001099 mPrimaryHWVsyncEnabled = true;
1100 }
1101}
1102
Jesse Hall948fe0c2013-10-14 12:56:09 -07001103void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001104 Mutex::Autolock _l(mHWVsyncLock);
1105 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001106 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1107 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108 mPrimaryDispSync.endResync();
1109 mPrimaryHWVsyncEnabled = false;
1110 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001111 if (makeUnavailable) {
1112 mHWVsyncAvailable = false;
1113 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114}
1115
Tim Murray4a4e4a22016-04-19 16:29:23 +00001116void SurfaceFlinger::resyncWithRateLimit() {
1117 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1118 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001119 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001120 }
1121}
1122
Steven Thomas3cfac282017-02-06 12:29:30 -08001123void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1124 nsecs_t timestamp) {
1125 Mutex::Autolock lock(mStateLock);
1126 // Ignore any vsyncs from the non-active hardware composer.
1127 if (composer != mHwc) {
1128 return;
1129 }
1130
Jamie Gennisd1700752013-10-14 12:22:52 -07001131 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001132
Jamie Gennisd1700752013-10-14 12:22:52 -07001133 { // Scope for the lock
1134 Mutex::Autolock _l(mHWVsyncLock);
1135 if (type == 0 && mPrimaryHWVsyncEnabled) {
1136 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001137 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001138 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001139
1140 if (needsHwVsync) {
1141 enableHardwareVsync();
1142 } else {
1143 disableHardwareVsync(false);
1144 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001145}
1146
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001147void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001148 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001149 *compositorTiming = mCompositorTiming;
1150}
1151
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001152void SurfaceFlinger::createDefaultDisplayDevice() {
1153 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1154 wp<IBinder> token = mBuiltinDisplays[type];
1155
1156 // All non-virtual displays are currently considered secure.
1157 const bool isSecure = true;
1158
1159 sp<IGraphicBufferProducer> producer;
1160 sp<IGraphicBufferConsumer> consumer;
1161 BufferQueue::createBufferQueue(&producer, &consumer);
1162
1163 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1164
1165 bool hasWideColorModes = false;
1166 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1167 for (android_color_mode_t colorMode : modes) {
1168 switch (colorMode) {
1169 case HAL_COLOR_MODE_DISPLAY_P3:
1170 case HAL_COLOR_MODE_ADOBE_RGB:
1171 case HAL_COLOR_MODE_DCI_P3:
1172 hasWideColorModes = true;
1173 break;
1174 default:
1175 break;
1176 }
1177 }
1178 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1179 token, fbs, producer, mRenderEngine->getEGLConfig(),
1180 hasWideColorModes && hasWideColorDisplay);
1181 mDisplays.add(token, hw);
1182 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1183 if (hasWideColorModes && hasWideColorDisplay) {
1184 defaultColorMode = HAL_COLOR_MODE_SRGB;
1185 }
1186 setActiveColorModeInternal(hw, defaultColorMode);
1187}
1188
1189void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001190 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001191
1192 if (composer->isUsingVrComposer()) {
1193 // We handle initializing the primary display device for the VR
1194 // window manager hwc explicitly at the time of transition.
1195 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1196 ALOGE("External displays are not supported by the vr hardware composer.");
1197 }
1198 return;
1199 }
1200
Dan Stoza9e56aa02015-11-02 13:00:03 -08001201 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1202 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001203 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1204 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205 } else {
1206 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001207 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001208 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001210 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001211 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1212 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001213 }
1214 setTransactionFlags(eDisplayTransactionNeeded);
1215
Andy McFadden9e9689c2012-10-10 18:17:51 -07001216 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001217 }
Mathias Agopian86303202012-07-24 22:46:10 -07001218}
1219
Steven Thomas3cfac282017-02-06 12:29:30 -08001220void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1221 Mutex::Autolock lock(mStateLock);
1222 if (composer == mHwc) {
1223 repaintEverything();
1224 } else {
1225 // This isn't from our current hardware composer. If it's a callback
1226 // from the real composer, forward the refresh request to vr
1227 // flinger. Otherwise ignore it.
1228 if (!composer->isUsingVrComposer()) {
1229 mVrFlinger->OnHardwareComposerRefresh();
1230 }
1231 }
1232}
1233
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 getHwComposer().setVsyncEnabled(disp,
1237 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001238}
1239
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001240void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1241 for (size_t i = 0; i < layers.size(); ++i) {
1242 layers[i]->clearHwcLayers();
1243 }
1244}
1245
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001246// Note: it is assumed the caller holds |mStateLock| when this is called
1247void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001248 disableHardwareVsync(true);
1249 clearHwcLayers(mDrawingState.layersSortedByZ);
1250 clearHwcLayers(mCurrentState.layersSortedByZ);
1251 // Clear the drawing state so that the logic inside of
1252 // handleTransactionLocked will fire. It will determine the delta between
1253 // mCurrentState and mDrawingState and re-apply all changes when we make the
1254 // transition.
1255 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001256 // Release virtual display hwcId during vr mode transition.
1257 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1258 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1259 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1260 displayDevice->disconnect(getHwComposer());
1261 }
1262 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001263 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001264 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001265}
1266
Steven Thomas050b2c82017-03-06 11:45:16 -08001267void SurfaceFlinger::updateVrFlinger() {
1268 if (!mVrFlinger)
1269 return;
1270 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1271 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001272 return;
1273 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001274
Steven Thomas050b2c82017-03-06 11:45:16 -08001275 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001276 // Construct new HWComposer without holding any locks.
1277 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001278
1279 // Set up the event handlers. This step is neccessary to initialize the internal state of
1280 // the hardware composer object properly. Our callbacks are designed such that if they are
1281 // triggered between now and the point where the display is properly re-initialized, they
1282 // will not have any effect, so this is safe to do here, before the lock is aquired.
1283 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001284 ALOGV("Vr HWC created");
1285 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001286
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001287 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001288
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001289 if (vrFlingerRequestsDisplay) {
1290 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001291
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292 mHwc = mVrHwc;
1293 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001295 } else {
1296 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001297
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001298 resetHwcLocked();
1299
1300 mHwc = mRealHwc;
1301 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303
1304 mVisibleRegionsDirty = true;
1305 invalidateHwcGeometry();
1306
1307 // Explicitly re-initialize the primary display. This is because some other
1308 // parts of this class rely on the primary display always being available.
1309 createDefaultDisplayDevice();
1310
1311 android_atomic_or(1, &mRepaintEverything);
1312 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001313}
1314
Mathias Agopian4fec8732012-06-29 14:12:52 -07001315void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001316 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001317 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001318 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001319 bool frameMissed = !mHadClientComposition &&
1320 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001321 (mPreviousPresentFence->getSignalTime() ==
1322 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001323 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001324 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001325 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001326 signalLayerUpdate();
1327 break;
1328 }
1329
Steven Thomas050b2c82017-03-06 11:45:16 -08001330 // Now that we're going to make it to the handleMessageTransaction()
1331 // call below it's safe to call updateVrFlinger(), which will
1332 // potentially trigger a display handoff.
1333 updateVrFlinger();
1334
Dan Stoza6b9454d2014-11-07 16:00:59 -08001335 bool refreshNeeded = handleMessageTransaction();
1336 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001337 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001338 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001339 // Signal a refresh if a transaction modified the window state,
1340 // a new buffer was latched, or if HWC has requested a full
1341 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001342 signalRefresh();
1343 }
1344 break;
1345 }
1346 case MessageQueue::REFRESH: {
1347 handleMessageRefresh();
1348 break;
1349 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001350 }
1351}
1352
Dan Stoza6b9454d2014-11-07 16:00:59 -08001353bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001354 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001355 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001356 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001357 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001358 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001359 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001360}
1361
Dan Stoza6b9454d2014-11-07 16:00:59 -08001362bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001363 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001364 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001365}
1366
1367void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001368 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001369
Pablo Ceballos40845df2016-01-25 17:41:15 -08001370 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001371
Brian Andersond6927fb2016-07-23 23:37:30 -07001372 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001373 rebuildLayerStacks();
1374 setUpHWComposer();
1375 doDebugFlashRegions();
1376 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001377 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001378
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001379 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001380
1381 mHadClientComposition = false;
1382 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1383 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1384 mHadClientComposition = mHadClientComposition ||
1385 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1386 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001387
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391void SurfaceFlinger::doDebugFlashRegions()
1392{
1393 // is debugging enabled
1394 if (CC_LIKELY(!mDebugRegion))
1395 return;
1396
1397 const bool repaintEverything = mRepaintEverything;
1398 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1399 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001400 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001401 // transform the dirty region into this screen's coordinate space
1402 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1403 if (!dirtyRegion.isEmpty()) {
1404 // redraw the whole screen
1405 doComposeSurfaces(hw, Region(hw->bounds()));
1406
1407 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001408 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001409 RenderEngine& engine(getRenderEngine());
1410 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1411
Mathias Agopianda27af92012-09-13 18:17:13 -07001412 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001413 }
1414 }
1415 }
1416
1417 postFramebuffer();
1418
1419 if (mDebugRegion > 1) {
1420 usleep(mDebugRegion * 1000);
1421 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001422
Dan Stoza9e56aa02015-11-02 13:00:03 -08001423 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001424 auto& displayDevice = mDisplays[displayId];
1425 if (!displayDevice->isDisplayOn()) {
1426 continue;
1427 }
1428
1429 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1431 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001432 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433}
1434
Brian Andersond6927fb2016-07-23 23:37:30 -07001435void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001437 ATRACE_CALL();
1438 ALOGV("preComposition");
1439
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001441 mDrawingState.traverseInZOrder([&](Layer* layer) {
1442 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 needExtraInvalidate = true;
1444 }
Robert Carr2047fae2016-11-28 14:09:09 -08001445 });
1446
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447 if (needExtraInvalidate) {
1448 signalLayerUpdate();
1449 }
1450}
1451
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001452void SurfaceFlinger::updateCompositorTiming(
1453 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1454 std::shared_ptr<FenceTime>& presentFenceTime) {
1455 // Update queue of past composite+present times and determine the
1456 // most recently known composite to present latency.
1457 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1458 nsecs_t compositeToPresentLatency = -1;
1459 while (!mCompositePresentTimes.empty()) {
1460 CompositePresentTime& cpt = mCompositePresentTimes.front();
1461 // Cached values should have been updated before calling this method,
1462 // which helps avoid duplicate syscalls.
1463 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1464 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1465 break;
1466 }
1467 compositeToPresentLatency = displayTime - cpt.composite;
1468 mCompositePresentTimes.pop();
1469 }
1470
1471 // Don't let mCompositePresentTimes grow unbounded, just in case.
1472 while (mCompositePresentTimes.size() > 16) {
1473 mCompositePresentTimes.pop();
1474 }
1475
Brian Andersond0010582017-03-07 13:20:31 -08001476 setCompositorTimingSnapped(
1477 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1478}
1479
1480void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1481 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482 // Integer division and modulo round toward 0 not -inf, so we need to
1483 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001484 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001485 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1486 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1487
Brian Andersond0010582017-03-07 13:20:31 -08001488 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1489 if (idealLatency <= 0) {
1490 idealLatency = vsyncInterval;
1491 }
1492
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 // Snap the latency to a value that removes scheduling jitter from the
1494 // composition and present times, which often have >1ms of jitter.
1495 // Reducing jitter is important if an app attempts to extrapolate
1496 // something (such as user input) to an accurate diasplay time.
1497 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1498 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001499 nsecs_t bias = vsyncInterval / 2;
1500 int64_t extraVsyncs =
1501 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1502 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1503 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504
Brian Andersond0010582017-03-07 13:20:31 -08001505 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1507 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001508 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001509}
1510
1511void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001513 ATRACE_CALL();
1514 ALOGV("postComposition");
1515
Brian Anderson3546a3f2016-07-14 11:51:14 -07001516 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001517 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001518 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001519 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001520 }
1521
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001522 // |mStateLock| not needed as we are on the main thread
1523 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001524
1525 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1526 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1527 glCompositionDoneFenceTime =
1528 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1529 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1530 } else {
1531 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1532 }
1533 mGlCompositionDoneTimeline.updateSignalTimes();
1534
Brian Anderson4e606e32017-03-16 15:34:57 -07001535 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1536 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1537 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001538 mDisplayTimeline.updateSignalTimes();
1539
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1541 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1542
1543 // We use the refreshStartTime which might be sampled a little later than
1544 // when we started doing work for this frame, but that should be okay
1545 // since updateCompositorTiming has snapping logic.
1546 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001547 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001548 CompositorTiming compositorTiming;
1549 {
1550 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1551 compositorTiming = mCompositorTiming;
1552 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001553
Robert Carr2047fae2016-11-28 14:09:09 -08001554 mDrawingState.traverseInZOrder([&](Layer* layer) {
1555 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001556 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001557 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001558 recordBufferingStats(layer->getName().string(),
1559 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001560 }
Robert Carr2047fae2016-11-28 14:09:09 -08001561 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001562
Brian Anderson4e606e32017-03-16 15:34:57 -07001563 if (presentFence->isValid()) {
1564 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001565 enableHardwareVsync();
1566 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001567 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001568 }
1569 }
1570
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001571 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001572 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001573 enableHardwareVsync();
1574 }
1575 }
1576
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001577 if (mAnimCompositionPending) {
1578 mAnimCompositionPending = false;
1579
Brian Anderson4e606e32017-03-16 15:34:57 -07001580 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001581 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001582 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001583 } else {
1584 // The HWC doesn't support present fences, so use the refresh
1585 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 nsecs_t presentTime =
1587 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001588 mAnimFrameTracker.setActualPresentTime(presentTime);
1589 }
1590 mAnimFrameTracker.advanceFrame();
1591 }
Dan Stozab90cf072015-03-05 11:05:59 -08001592
1593 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1594 return;
1595 }
1596
1597 nsecs_t currentTime = systemTime();
1598 if (mHasPoweredOff) {
1599 mHasPoweredOff = false;
1600 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001601 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001602 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001603 if (numPeriods < NUM_BUCKETS - 1) {
1604 mFrameBuckets[numPeriods] += elapsedTime;
1605 } else {
1606 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1607 }
1608 mTotalTime += elapsedTime;
1609 }
1610 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001611}
1612
1613void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001614 ATRACE_CALL();
1615 ALOGV("rebuildLayerStacks");
1616
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001618 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1619 ATRACE_CALL();
1620 mVisibleRegionsDirty = false;
1621 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001622
Jeff Sharkey76488112017-02-27 14:15:18 -07001623 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1624 Region opaqueRegion;
1625 Region dirtyRegion;
1626 Vector<sp<Layer>> layersSortedByZ;
1627 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1628 const Transform& tr(displayDevice->getTransform());
1629 const Rect bounds(displayDevice->getBounds());
1630 if (displayDevice->isDisplayOn()) {
1631 computeVisibleRegions(
1632 displayDevice->getLayerStack(), dirtyRegion,
1633 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001634
Jeff Sharkey76488112017-02-27 14:15:18 -07001635 mDrawingState.traverseInZOrder([&](Layer* layer) {
1636 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1637 Region drawRegion(tr.transform(
1638 layer->visibleNonTransparentRegion));
1639 drawRegion.andSelf(bounds);
1640 if (!drawRegion.isEmpty()) {
1641 layersSortedByZ.add(layer);
1642 } else {
1643 // Clear out the HWC layer if this layer was
1644 // previously visible, but no longer is
1645 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1646 nullptr);
1647 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001648 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001649 // WM changes displayDevice->layerStack upon sleep/awake.
1650 // Here we make sure we delete the HWC layers even if
1651 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001652 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1653 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001654 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001655 });
1656 }
1657 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1658 displayDevice->undefinedRegion.set(bounds);
1659 displayDevice->undefinedRegion.subtractSelf(
1660 tr.transform(opaqueRegion));
1661 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001662 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001663 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001665
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001666// pickColorMode translates a given dataspace into the best available color mode.
1667// Currently only support sRGB and Display-P3.
1668android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1669 switch (dataSpace) {
1670 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1671 // system expects.
1672 case HAL_DATASPACE_UNKNOWN:
1673 case HAL_DATASPACE_SRGB:
1674 case HAL_DATASPACE_V0_SRGB:
1675 return HAL_COLOR_MODE_SRGB;
1676 break;
1677
1678 case HAL_DATASPACE_DISPLAY_P3:
1679 return HAL_COLOR_MODE_DISPLAY_P3;
1680 break;
1681
1682 default:
1683 // TODO (courtneygo): Do we want to assert an error here?
1684 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1685 dataSpace);
1686 return HAL_COLOR_MODE_SRGB;
1687 break;
1688 }
1689}
1690
1691android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1692 // Only support sRGB and Display-P3 right now.
1693 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1694 return HAL_DATASPACE_DISPLAY_P3;
1695 }
1696 return HAL_DATASPACE_V0_SRGB;
1697}
1698
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001700 ATRACE_CALL();
1701 ALOGV("setUpHWComposer");
1702
Jesse Hall028dc8f2013-08-20 16:35:32 -07001703 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001704 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1705 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1706 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1707
1708 // If nothing has changed (!dirty), don't recompose.
1709 // If something changed, but we don't currently have any visible layers,
1710 // and didn't when we last did a composition, then skip it this time.
1711 // The second rule does two things:
1712 // - When all layers are removed from a display, we'll emit one black
1713 // frame, then nothing more until we get new layers.
1714 // - When a display is created with a private layer stack, we won't
1715 // emit any black frames until a layer is added to the layer stack.
1716 bool mustRecompose = dirty && !(empty && wasEmpty);
1717
1718 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1719 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1720 mustRecompose ? "doing" : "skipping",
1721 dirty ? "+" : "-",
1722 empty ? "+" : "-",
1723 wasEmpty ? "+" : "-");
1724
Dan Stoza71433162014-02-04 16:22:36 -08001725 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001726
1727 if (mustRecompose) {
1728 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1729 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001730 }
1731
Dan Stoza9e56aa02015-11-02 13:00:03 -08001732 // build the h/w work list
1733 if (CC_UNLIKELY(mGeometryInvalid)) {
1734 mGeometryInvalid = false;
1735 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1736 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1737 const auto hwcId = displayDevice->getHwcDisplayId();
1738 if (hwcId >= 0) {
1739 const Vector<sp<Layer>>& currentLayers(
1740 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001741 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001742 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001743 if (!layer->hasHwcLayer(hwcId)) {
1744 auto hwcLayer = mHwc->createLayer(hwcId);
1745 if (hwcLayer) {
1746 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1747 } else {
1748 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001750 }
1751 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001752
Robert Carrae060832016-11-28 10:51:00 -08001753 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001754 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001756 }
1757 }
1758 }
1759 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 }
Riley Andrews03414a12014-07-01 14:22:59 -07001761
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001762
1763 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1764
Dan Stoza9e56aa02015-11-02 13:00:03 -08001765 // Set the per-frame data
1766 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1767 auto& displayDevice = mDisplays[displayId];
1768 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001769
Dan Stoza9e56aa02015-11-02 13:00:03 -08001770 if (hwcId < 0) {
1771 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001772 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001773 if (colorMatrix != mPreviousColorMatrix) {
1774 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1775 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1776 "display %zd: %d", displayId, result);
1777 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001778 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1779 layer->setPerFrameData(displayDevice);
1780 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001781
1782 if (hasWideColorDisplay) {
1783 android_color_mode newColorMode;
1784 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1785
1786 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1787 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1788 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1789 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1790 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1791 }
1792 newColorMode = pickColorMode(newDataSpace);
1793
1794 setActiveColorModeInternal(displayDevice, newColorMode);
1795 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 }
1797
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001798 mPreviousColorMatrix = colorMatrix;
1799
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001801 auto& displayDevice = mDisplays[displayId];
1802 if (!displayDevice->isDisplayOn()) {
1803 continue;
1804 }
1805
1806 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1808 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001809 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001811
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812void SurfaceFlinger::doComposition() {
1813 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 ALOGV("doComposition");
1815
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001816 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001817 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001818 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001819 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820 // transform the dirty region into this screen's coordinate space
1821 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001822
1823 // repaint the framebuffer (if needed)
1824 doDisplayComposition(hw, dirtyRegion);
1825
Mathias Agopiancd60f992012-08-16 16:28:27 -07001826 hw->dirtyRegion.clear();
1827 hw->flip(hw->swapRegion);
1828 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001829 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001831 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001832}
1833
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001834void SurfaceFlinger::postFramebuffer()
1835{
Mathias Agopian841cde52012-03-01 15:44:37 -08001836 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001837 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001838
Mathias Agopiana44b0412011-10-16 18:46:35 -07001839 const nsecs_t now = systemTime();
1840 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001841
Dan Stoza9e56aa02015-11-02 13:00:03 -08001842 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1843 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001844 if (!displayDevice->isDisplayOn()) {
1845 continue;
1846 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 const auto hwcId = displayDevice->getHwcDisplayId();
1848 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001849 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001850 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001851 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001852 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1854 sp<Fence> releaseFence = Fence::NO_FENCE;
1855 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1856 releaseFence = displayDevice->getClientTargetAcquireFence();
1857 } else {
1858 auto hwcLayer = layer->getHwcLayer(hwcId);
1859 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001860 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 layer->onLayerDisplayed(releaseFence);
1862 }
1863 if (hwcId >= 0) {
1864 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001865 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001866 }
1867
Mathias Agopiana44b0412011-10-16 18:46:35 -07001868 mLastSwapBufferTime = systemTime() - now;
1869 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001870
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001871 // |mStateLock| not needed as we are on the main thread
1872 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001873 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1874 logFrameStats();
1875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001876}
1877
Mathias Agopian87baae12012-07-31 12:38:26 -07001878void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001879{
Mathias Agopian841cde52012-03-01 15:44:37 -08001880 ATRACE_CALL();
1881
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001882 // here we keep a copy of the drawing state (that is the state that's
1883 // going to be overwritten by handleTransactionLocked()) outside of
1884 // mStateLock so that the side-effects of the State assignment
1885 // don't happen with mStateLock held (which can cause deadlocks).
1886 State drawingState(mDrawingState);
1887
Mathias Agopianca4d3602011-05-19 15:38:14 -07001888 Mutex::Autolock _l(mStateLock);
1889 const nsecs_t now = systemTime();
1890 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001891
Mathias Agopianca4d3602011-05-19 15:38:14 -07001892 // Here we're guaranteed that some transaction flags are set
1893 // so we can call handleTransactionLocked() unconditionally.
1894 // We call getTransactionFlags(), which will also clear the flags,
1895 // with mStateLock held to guarantee that mCurrentState won't change
1896 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001897
Mathias Agopiane57f2922012-08-09 16:29:12 -07001898 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001899 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001900
Mathias Agopianca4d3602011-05-19 15:38:14 -07001901 mLastTransactionTime = systemTime() - now;
1902 mDebugInTransaction = 0;
1903 invalidateHwcGeometry();
1904 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001905}
1906
Mathias Agopian87baae12012-07-31 12:38:26 -07001907void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001908{
Dan Stoza7dde5992015-05-22 09:51:44 -07001909 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001910 mCurrentState.traverseInZOrder([](Layer* layer) {
1911 layer->notifyAvailableFrames();
1912 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001913
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001914 /*
1915 * Traversal of the children
1916 * (perform the transaction for each of them if needed)
1917 */
1918
Mathias Agopian3559b072012-08-15 13:46:03 -07001919 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001920 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001921 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001922 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001923
1924 const uint32_t flags = layer->doTransaction(0);
1925 if (flags & Layer::eVisibleRegion)
1926 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001927 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001928 }
1929
1930 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001931 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001932 */
1933
Mathias Agopiane57f2922012-08-09 16:29:12 -07001934 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001935 // here we take advantage of Vector's copy-on-write semantics to
1936 // improve performance by skipping the transaction entirely when
1937 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001938 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1939 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001940 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001941 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001942 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001943 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001944
1945 // find the displays that were removed
1946 // (ie: in drawing state but not in current state)
1947 // also handle displays that changed
1948 // (ie: displays that are in both lists)
1949 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001950 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1951 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001952 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001953 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001954 // Call makeCurrent() on the primary display so we can
1955 // be sure that nothing associated with this display
1956 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001957 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001958 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001959 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07001960 if (hw != NULL)
1961 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001962 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001963 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001964 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001965 } else {
1966 ALOGW("trying to remove the main display");
1967 }
1968 } else {
1969 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001970 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001971 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001972 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1973 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001974 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001975 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001976 // recreating the DisplayDevice, so we just remove it
1977 // from the drawing state, so that it get re-added
1978 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001979 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07001980 if (hw != NULL)
1981 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001982 mDisplays.removeItem(display);
1983 mDrawingState.displays.removeItemsAt(i);
1984 dc--; i--;
1985 // at this point we must loop to the next item
1986 continue;
1987 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001988
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001989 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001990 if (disp != NULL) {
1991 if (state.layerStack != draw[i].layerStack) {
1992 disp->setLayerStack(state.layerStack);
1993 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001994 if ((state.orientation != draw[i].orientation)
1995 || (state.viewport != draw[i].viewport)
1996 || (state.frame != draw[i].frame))
1997 {
1998 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001999 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002000 }
Michael Lentine47e45402014-07-18 15:34:25 -07002001 if (state.width != draw[i].width || state.height != draw[i].height) {
2002 disp->setDisplaySize(state.width, state.height);
2003 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002004 }
2005 }
2006 }
2007
2008 // find displays that were added
2009 // (ie: in current state but not in drawing state)
2010 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002011 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002012 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002013
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002014 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002015 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002016 sp<IGraphicBufferProducer> bqProducer;
2017 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002018 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002019
Dan Stoza9e56aa02015-11-02 13:00:03 -08002020 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002021 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002022 // Virtual displays without a surface are dormant:
2023 // they have external state (layer stack, projection,
2024 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002025 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002026
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002027 // Allow VR composer to use virtual displays.
2028 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002029 int width = 0;
2030 int status = state.surface->query(
2031 NATIVE_WINDOW_WIDTH, &width);
2032 ALOGE_IF(status != NO_ERROR,
2033 "Unable to query width (%d)", status);
2034 int height = 0;
2035 status = state.surface->query(
2036 NATIVE_WINDOW_HEIGHT, &height);
2037 ALOGE_IF(status != NO_ERROR,
2038 "Unable to query height (%d)", status);
2039 int intFormat = 0;
2040 status = state.surface->query(
2041 NATIVE_WINDOW_FORMAT, &intFormat);
2042 ALOGE_IF(status != NO_ERROR,
2043 "Unable to query format (%d)", status);
2044 auto format = static_cast<android_pixel_format_t>(
2045 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002046
Dan Stoza8cf150a2016-08-02 10:27:31 -07002047 mHwc->allocateVirtualDisplay(width, height, &format,
2048 &hwcId);
2049 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050
Dan Stoza5cf424b2016-05-20 14:02:39 -07002051 // TODO: Plumb requested format back up to consumer
2052
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 sp<VirtualDisplaySurface> vds =
2054 new VirtualDisplaySurface(*mHwc,
2055 hwcId, state.surface, bqProducer,
2056 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002057
2058 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002059 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002060 }
2061 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002062 ALOGE_IF(state.surface!=NULL,
2063 "adding a supported display, but rendering "
2064 "surface is provided (%p), ignoring it",
2065 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002066
2067 hwcId = state.type;
2068 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2069 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002070 }
2071
2072 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002073 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002074 sp<DisplayDevice> hw =
2075 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2076 dispSurface, producer,
2077 mRenderEngine->getEGLConfig(),
2078 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002079 hw->setLayerStack(state.layerStack);
2080 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002081 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002082 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002083 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002085 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002086 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002087 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002088 }
2089 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002090 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002091 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002092
Mathias Agopian84300952012-11-21 16:02:13 -08002093 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2094 // The transform hint might have changed for some layers
2095 // (either because a display has changed, or because a layer
2096 // as changed).
2097 //
2098 // Walk through all the layers in currentLayers,
2099 // and update their transform hint.
2100 //
2101 // If a layer is visible only on a single display, then that
2102 // display is used to calculate the hint, otherwise we use the
2103 // default display.
2104 //
2105 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2106 // the hint is set before we acquire a buffer from the surface texture.
2107 //
2108 // NOTE: layer transactions have taken place already, so we use their
2109 // drawing state. However, SurfaceFlinger's own transaction has not
2110 // happened yet, so we must use the current state layer list
2111 // (soon to become the drawing state list).
2112 //
2113 sp<const DisplayDevice> disp;
2114 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002115 bool first = true;
2116 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002117 // NOTE: we rely on the fact that layers are sorted by
2118 // layerStack first (so we don't have to traverse the list
2119 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002120 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002121 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002122 currentlayerStack = layerStack;
2123 // figure out if this layerstack is mirrored
2124 // (more than one display) if so, pick the default display,
2125 // if not, pick the only display it's on.
2126 disp.clear();
2127 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2128 sp<const DisplayDevice> hw(mDisplays[dpy]);
2129 if (hw->getLayerStack() == currentlayerStack) {
2130 if (disp == NULL) {
2131 disp = hw;
2132 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002133 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002134 break;
2135 }
2136 }
2137 }
2138 }
Chet Haase91d25932013-04-11 15:24:55 -07002139 if (disp == NULL) {
2140 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2141 // redraw after transform hint changes. See bug 8508397.
2142
2143 // could be null when this layer is using a layerStack
2144 // that is not visible on any display. Also can occur at
2145 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002146 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002147 }
Chet Haase91d25932013-04-11 15:24:55 -07002148 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002149
2150 first = false;
2151 });
Mathias Agopian84300952012-11-21 16:02:13 -08002152 }
2153
2154
Mathias Agopian3559b072012-08-15 13:46:03 -07002155 /*
2156 * Perform our own transaction if needed
2157 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002158
2159 if (mLayersAdded) {
2160 mLayersAdded = false;
2161 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002162 mVisibleRegionsDirty = true;
2163 }
2164
2165 // some layers might have been removed, so
2166 // we need to update the regions they're exposing.
2167 if (mLayersRemoved) {
2168 mLayersRemoved = false;
2169 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002170 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002171 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002172 // this layer is not visible anymore
2173 // TODO: we could traverse the tree from front to back and
2174 // compute the actual visible region
2175 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 Region visibleReg;
2177 visibleReg.set(layer->computeScreenBounds());
2178 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002179 }
Robert Carr2047fae2016-11-28 14:09:09 -08002180 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002181 }
2182
2183 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002184
2185 updateCursorAsync();
2186}
2187
2188void SurfaceFlinger::updateCursorAsync()
2189{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2191 auto& displayDevice = mDisplays[displayId];
2192 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002193 continue;
2194 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195
2196 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2197 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002198 }
2199 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002200}
2201
2202void SurfaceFlinger::commitTransaction()
2203{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002204 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002205 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002206 for (const auto& l : mLayersPendingRemoval) {
2207 recordBufferingStats(l->getName().string(),
2208 l->getOccupancyHistory(true));
2209 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002210 }
2211 mLayersPendingRemoval.clear();
2212 }
2213
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002214 // If this transaction is part of a window animation then the next frame
2215 // we composite should be considered an animation as well.
2216 mAnimCompositionPending = mAnimTransactionPending;
2217
Mathias Agopian4fec8732012-06-29 14:12:52 -07002218 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002219 mDrawingState.traverseInZOrder([](Layer* layer) {
2220 layer->commitChildList();
2221 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002222 mTransactionPending = false;
2223 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002225}
2226
Robert Carr2047fae2016-11-28 14:09:09 -08002227void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002228 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002229{
Mathias Agopian841cde52012-03-01 15:44:37 -08002230 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233 Region aboveOpaqueLayers;
2234 Region aboveCoveredLayers;
2235 Region dirty;
2236
Mathias Agopian87baae12012-07-31 12:38:26 -07002237 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238
Robert Carr2047fae2016-11-28 14:09:09 -08002239 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002241 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242
Jesse Hall01e29052013-02-19 16:13:35 -08002243 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002244 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002245 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002246
Mathias Agopianab028732010-03-16 16:41:46 -07002247 /*
2248 * opaqueRegion: area of a surface that is fully opaque.
2249 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002251
2252 /*
2253 * visibleRegion: area of a surface that is visible on screen
2254 * and not fully transparent. This is essentially the layer's
2255 * footprint minus the opaque regions above it.
2256 * Areas covered by a translucent surface are considered visible.
2257 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002259
2260 /*
2261 * coveredRegion: area of a surface that is covered by all
2262 * visible regions above it (which includes the translucent areas).
2263 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002264 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002265
Jesse Halla8026d22012-09-25 13:25:04 -07002266 /*
2267 * transparentRegion: area of a surface that is hinted to be completely
2268 * transparent. This is only used to tell when the layer has no visible
2269 * non-transparent regions and can be removed from the layer list. It
2270 * does not affect the visibleRegion of this layer or any layers
2271 * beneath it. The hint may not be correct if apps don't respect the
2272 * SurfaceView restrictions (which, sadly, some don't).
2273 */
2274 Region transparentRegion;
2275
Mathias Agopianab028732010-03-16 16:41:46 -07002276
2277 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002278 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002279 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002280 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002283 if (!visibleRegion.isEmpty()) {
2284 // Remove the transparent area from the visible region
2285 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002286 if (tr.preserveRects()) {
2287 // transform the transparent region
2288 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002290 // transformation too complex, can't do the
2291 // transparent region optimization.
2292 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 }
Mathias Agopianab028732010-03-16 16:41:46 -07002294 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295
Mathias Agopianab028732010-03-16 16:41:46 -07002296 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002297 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002298 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002299 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2300 // the opaque region is the layer's footprint
2301 opaqueRegion = visibleRegion;
2302 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303 }
2304 }
2305
Mathias Agopianab028732010-03-16 16:41:46 -07002306 // Clip the covered region to the visible region
2307 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2308
2309 // Update aboveCoveredLayers for next (lower) layer
2310 aboveCoveredLayers.orSelf(visibleRegion);
2311
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 // subtract the opaque region covered by the layers above us
2313 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314
2315 // compute this layer's dirty region
2316 if (layer->contentDirty) {
2317 // we need to invalidate the whole region
2318 dirty = visibleRegion;
2319 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002320 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 layer->contentDirty = false;
2322 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002323 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002324 * the exposed region consists of two components:
2325 * 1) what's VISIBLE now and was COVERED before
2326 * 2) what's EXPOSED now less what was EXPOSED before
2327 *
2328 * note that (1) is conservative, we start with the whole
2329 * visible region but only keep what used to be covered by
2330 * something -- which mean it may have been exposed.
2331 *
2332 * (2) handles areas that were not covered by anything but got
2333 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002334 */
Mathias Agopianab028732010-03-16 16:41:46 -07002335 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002336 const Region oldVisibleRegion = layer->visibleRegion;
2337 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002338 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2339 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 }
2341 dirty.subtractSelf(aboveOpaqueLayers);
2342
2343 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002344 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345
Mathias Agopianab028732010-03-16 16:41:46 -07002346 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002348
Jesse Halla8026d22012-09-25 13:25:04 -07002349 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 layer->setVisibleRegion(visibleRegion);
2351 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002352 layer->setVisibleNonTransparentRegion(
2353 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002354 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357}
2358
Mathias Agopian87baae12012-07-31 12:38:26 -07002359void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2360 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002361 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002362 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2363 if (hw->getLayerStack() == layerStack) {
2364 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002365 }
2366 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002367}
2368
Dan Stoza6b9454d2014-11-07 16:00:59 -08002369bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002371 ALOGV("handlePageFlip");
2372
Brian Andersond6927fb2016-07-23 23:37:30 -07002373 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374
Mathias Agopian4fec8732012-06-29 14:12:52 -07002375 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002376 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002377 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002378
2379 // Store the set of layers that need updates. This set must not change as
2380 // buffers are being latched, as this could result in a deadlock.
2381 // Example: Two producers share the same command stream and:
2382 // 1.) Layer 0 is latched
2383 // 2.) Layer 0 gets a new frame
2384 // 2.) Layer 1 gets a new frame
2385 // 3.) Layer 1 is latched.
2386 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2387 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002388 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002389 if (layer->hasQueuedFrame()) {
2390 frameQueued = true;
2391 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002392 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002393 } else {
2394 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002395 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002396 } else {
2397 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002398 }
Robert Carr2047fae2016-11-28 14:09:09 -08002399 });
2400
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002402 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002403 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002404 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002405 if (!dirty.isEmpty()) {
2406 newDataLatched = true;
2407 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002408 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002409
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002410 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002411
2412 // If we will need to wake up at some time in the future to deal with a
2413 // queued frame that shouldn't be displayed during this vsync period, wake
2414 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002415 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002416 signalLayerUpdate();
2417 }
2418
2419 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002420 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421}
2422
Mathias Agopianad456f92011-01-13 17:53:01 -08002423void SurfaceFlinger::invalidateHwcGeometry()
2424{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002425 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002426}
2427
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002428
Fabien Sanglard830b8472016-11-30 16:35:58 -08002429void SurfaceFlinger::doDisplayComposition(
2430 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002431 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432{
Dan Stoza71433162014-02-04 16:22:36 -08002433 // We only need to actually compose the display if:
2434 // 1) It is being handled by hardware composer, which may need this to
2435 // keep its virtual display state machine in sync, or
2436 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002437 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002438 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002439 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002440 return;
2441 }
2442
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 ALOGV("doDisplayComposition");
2444
Mathias Agopian87baae12012-07-31 12:38:26 -07002445 Region dirtyRegion(inDirtyRegion);
2446
Mathias Agopianb8a55602009-06-26 19:06:36 -07002447 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002448 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002449
Fabien Sanglard830b8472016-11-30 16:35:58 -08002450 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002451 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002452 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2453 // takes a rectangle, we must make sure to update that whole
2454 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002455 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002456 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002457 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002458 // We need to redraw the rectangle that will be updated
2459 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002460 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002461 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002462 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002463 } else {
2464 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002465 dirtyRegion.set(displayDevice->bounds());
2466 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 }
2468 }
2469
Fabien Sanglard830b8472016-11-30 16:35:58 -08002470 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002472 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002473 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002474
2475 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002476 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477}
2478
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479bool SurfaceFlinger::doComposeSurfaces(
2480 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002481{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002483
Dan Stoza9e56aa02015-11-02 13:00:03 -08002484 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002485
2486 mat4 oldColorMatrix;
2487 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2488 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2489 if (applyColorMatrix) {
2490 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2491 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2492 }
2493
Dan Stoza9e56aa02015-11-02 13:00:03 -08002494 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2495 if (hasClientComposition) {
2496 ALOGV("hasClientComposition");
2497
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002498#ifdef USE_HWC2
2499 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2500 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2501#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002502 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002503 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002505 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002506
2507 // |mStateLock| not needed as we are on the main thread
2508 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002509 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2510 }
2511 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002512 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002513
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002514 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2516 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002517 // when using overlays, we assume a fully transparent framebuffer
2518 // NOTE: we could reduce how much we need to clear, for instance
2519 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002520 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002521 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002523 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002524 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002525 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002526
2527 // we remove the scissor part
2528 // we're left with the letterbox region
2529 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002531
2532 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002534
2535 // but limit it to the dirty region
2536 region.andSelf(dirty);
2537
Mathias Agopianb9494d52012-04-18 02:28:45 -07002538 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002539 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002540 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002541 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002542 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002543 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002544
Dan Stoza9e56aa02015-11-02 13:00:03 -08002545 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002546 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002547 // scissor on the main display. It should never be needed
2548 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 const Rect& bounds(displayDevice->getBounds());
2550 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002551 if (scissor != bounds) {
2552 // scissor doesn't match the screen's dimensions, so we
2553 // need to clear everything outside of it and enable
2554 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002555
Mathias Agopianf45c5102012-10-24 16:29:17 -07002556 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002557 const uint32_t height = displayDevice->getHeight();
2558 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002559 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002560 }
2561 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002562 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002563
Mathias Agopian85d751c2012-08-29 16:59:24 -07002564 /*
2565 * and then, render the layers targeted at the framebuffer
2566 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002567
Dan Stoza9e56aa02015-11-02 13:00:03 -08002568 ALOGV("Rendering client layers");
2569 const Transform& displayTransform = displayDevice->getTransform();
2570 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002571 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002572 bool firstLayer = true;
2573 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2574 const Region clip(dirty.intersect(
2575 displayTransform.transform(layer->visibleRegion)));
2576 ALOGV("Layer: %s", layer->getName().string());
2577 ALOGV(" Composition type: %s",
2578 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002579 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 switch (layer->getCompositionType(hwcId)) {
2581 case HWC2::Composition::Cursor:
2582 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002583 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002585 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2587 layer->isOpaque(state) && (state.alpha == 1.0f)
2588 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002589 // never clear the very first layer since we're
2590 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002591 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002592 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002593 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002594 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 case HWC2::Composition::Client: {
2596 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002597 break;
2598 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002600 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002601 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 } else {
2603 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002604 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002606 }
2607 } else {
2608 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002610 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002612 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002614 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002615 }
2616 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002617
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002618 if (applyColorMatrix) {
2619 getRenderEngine().setupColorTransform(oldColorMatrix);
2620 }
2621
Mathias Agopianf45c5102012-10-24 16:29:17 -07002622 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002623 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002624 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002625}
2626
Fabien Sanglard830b8472016-11-30 16:35:58 -08002627void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2628 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002629 RenderEngine& engine(getRenderEngine());
2630 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631}
2632
Dan Stoza7d89d062015-04-30 13:29:25 -07002633status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002634 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002635 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002636 const sp<Layer>& lbc,
2637 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002638{
Dan Stoza7d89d062015-04-30 13:29:25 -07002639 // add this layer to the current state list
2640 {
2641 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002643 return NO_MEMORY;
2644 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002645 if (parent == nullptr) {
2646 mCurrentState.layersSortedByZ.add(lbc);
2647 } else {
2648 parent->addChild(lbc);
2649 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002650 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002651 mLayersAdded = true;
2652 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002653 }
2654
Mathias Agopian96f08192010-06-02 23:28:45 -07002655 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002656 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002657
Dan Stoza7d89d062015-04-30 13:29:25 -07002658 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002659}
2660
Robert Carr9524cb32017-02-13 11:32:32 -08002661status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002662 Mutex::Autolock _l(mStateLock);
2663
Robert Carr1f0a16a2016-10-24 16:27:39 -07002664 const auto& p = layer->getParent();
2665 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2666 mCurrentState.layersSortedByZ.remove(layer);
2667
Robert Carr136e2f62017-02-08 17:54:29 -08002668 // As a matter of normal operation, the LayerCleaner will produce a second
2669 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2670 // so we will succeed in promoting it, but it's already been removed
2671 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2672 // otherwise something has gone wrong and we are leaking the layer.
2673 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2675 layer->getName().string(),
2676 (p != nullptr) ? p->getName().string() : "no-parent");
2677 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002678 } else if (index < 0) {
2679 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002680 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681
2682 mLayersPendingRemoval.add(layer);
2683 mLayersRemoved = true;
2684 mNumLayers--;
2685 setTransactionFlags(eTransactionNeeded);
2686 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687}
2688
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002689uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002690 return android_atomic_release_load(&mTransactionFlags);
2691}
2692
Mathias Agopian3f844832013-08-07 21:24:32 -07002693uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2695}
2696
Mathias Agopian3f844832013-08-07 21:24:32 -07002697uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2699 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002700 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 }
2702 return old;
2703}
2704
Mathias Agopian8b33f032012-07-24 20:43:54 -07002705void SurfaceFlinger::setTransactionState(
2706 const Vector<ComposerState>& state,
2707 const Vector<DisplayState>& displays,
2708 uint32_t flags)
2709{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002710 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002711 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002712 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002713
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002714 if (flags & eAnimation) {
2715 // For window updates that are part of an animation we must wait for
2716 // previous animation "frames" to be handled.
2717 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002718 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002719 if (CC_UNLIKELY(err != NO_ERROR)) {
2720 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002721 // caller after a few seconds.
2722 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2723 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002724 mAnimTransactionPending = false;
2725 break;
2726 }
2727 }
2728 }
2729
Mathias Agopiane57f2922012-08-09 16:29:12 -07002730 size_t count = displays.size();
2731 for (size_t i=0 ; i<count ; i++) {
2732 const DisplayState& s(displays[i]);
2733 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002734 }
2735
Mathias Agopiane57f2922012-08-09 16:29:12 -07002736 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002737 for (size_t i=0 ; i<count ; i++) {
2738 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002739 // Here we need to check that the interface we're given is indeed
2740 // one of our own. A malicious client could give us a NULL
2741 // IInterface, or one of its own or even one of our own but a
2742 // different type. All these situations would cause us to crash.
2743 //
2744 // NOTE: it would be better to use RTTI as we could directly check
2745 // that we have a Client*. however, RTTI is disabled in Android.
2746 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002747 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002748 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002749 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002750 sp<Client> client( static_cast<Client *>(s.client.get()) );
2751 transactionFlags |= setClientStateLocked(client, s.state);
2752 }
2753 }
2754 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002755 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002756
Robert Carr2a7dbb42016-05-24 11:41:28 -07002757 // If a synchronous transaction is explicitly requested without any changes,
2758 // force a transaction anyway. This can be used as a flush mechanism for
2759 // previous async transactions.
2760 if (transactionFlags == 0 && (flags & eSynchronous)) {
2761 transactionFlags = eTransactionNeeded;
2762 }
2763
Mathias Agopian386aa982011-11-07 21:58:03 -08002764 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002765 if (mInterceptor.isEnabled()) {
2766 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2767 }
Irvel468051e2016-06-13 16:44:44 -07002768
Mathias Agopian386aa982011-11-07 21:58:03 -08002769 // this triggers the transaction
2770 setTransactionFlags(transactionFlags);
2771
2772 // if this is a synchronous transaction, wait for it to take effect
2773 // before returning.
2774 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002775 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002776 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002777 if (flags & eAnimation) {
2778 mAnimTransactionPending = true;
2779 }
2780 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002781 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2782 if (CC_UNLIKELY(err != NO_ERROR)) {
2783 // just in case something goes wrong in SF, return to the
2784 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002785 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2786 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002787 break;
2788 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002789 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 }
2791}
2792
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2794{
Jesse Hall9a143922012-10-04 16:29:19 -07002795 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2796 if (dpyIdx < 0)
2797 return 0;
2798
Mathias Agopiane57f2922012-08-09 16:29:12 -07002799 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002800 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002801 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002802 const uint32_t what = s.what;
2803 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002804 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002805 disp.surface = s.surface;
2806 flags |= eDisplayTransactionNeeded;
2807 }
2808 }
2809 if (what & DisplayState::eLayerStackChanged) {
2810 if (disp.layerStack != s.layerStack) {
2811 disp.layerStack = s.layerStack;
2812 flags |= eDisplayTransactionNeeded;
2813 }
2814 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002815 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 if (disp.orientation != s.orientation) {
2817 disp.orientation = s.orientation;
2818 flags |= eDisplayTransactionNeeded;
2819 }
2820 if (disp.frame != s.frame) {
2821 disp.frame = s.frame;
2822 flags |= eDisplayTransactionNeeded;
2823 }
2824 if (disp.viewport != s.viewport) {
2825 disp.viewport = s.viewport;
2826 flags |= eDisplayTransactionNeeded;
2827 }
2828 }
Michael Lentine47e45402014-07-18 15:34:25 -07002829 if (what & DisplayState::eDisplaySizeChanged) {
2830 if (disp.width != s.width) {
2831 disp.width = s.width;
2832 flags |= eDisplayTransactionNeeded;
2833 }
2834 if (disp.height != s.height) {
2835 disp.height = s.height;
2836 flags |= eDisplayTransactionNeeded;
2837 }
2838 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002839 }
2840 return flags;
2841}
2842
2843uint32_t SurfaceFlinger::setClientStateLocked(
2844 const sp<Client>& client,
2845 const layer_state_t& s)
2846{
2847 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002848 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002849 if (layer != 0) {
2850 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002851 bool geometryAppliesWithResize =
2852 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002853 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002854 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002855 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002856 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002857 }
2858 if (what & layer_state_t::eLayerChanged) {
2859 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002860 const auto& p = layer->getParent();
2861 if (p == nullptr) {
2862 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2863 if (layer->setLayer(s.z) && idx >= 0) {
2864 mCurrentState.layersSortedByZ.removeAt(idx);
2865 mCurrentState.layersSortedByZ.add(layer);
2866 // we need traversal (state changed)
2867 // AND transaction (list changed)
2868 flags |= eTransactionNeeded|eTraversalNeeded;
2869 }
2870 } else {
2871 if (p->setChildLayer(layer, s.z)) {
2872 flags |= eTransactionNeeded|eTraversalNeeded;
2873 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002874 }
2875 }
Robert Carrdb66e622017-04-10 16:55:57 -07002876 if (what & layer_state_t::eRelativeLayerChanged) {
2877 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2878 flags |= eTransactionNeeded|eTraversalNeeded;
2879 }
2880 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002881 if (what & layer_state_t::eSizeChanged) {
2882 if (layer->setSize(s.w, s.h)) {
2883 flags |= eTraversalNeeded;
2884 }
2885 }
2886 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002887 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002888 flags |= eTraversalNeeded;
2889 }
2890 if (what & layer_state_t::eMatrixChanged) {
2891 if (layer->setMatrix(s.matrix))
2892 flags |= eTraversalNeeded;
2893 }
2894 if (what & layer_state_t::eTransparentRegionChanged) {
2895 if (layer->setTransparentRegionHint(s.transparentRegion))
2896 flags |= eTraversalNeeded;
2897 }
Dan Stoza23116082015-06-18 14:58:39 -07002898 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002899 if (layer->setFlags(s.flags, s.mask))
2900 flags |= eTraversalNeeded;
2901 }
2902 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002903 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002904 flags |= eTraversalNeeded;
2905 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002906 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002907 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002908 flags |= eTraversalNeeded;
2909 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002911 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 // We only allow setting layer stacks for top level layers,
2913 // everything else inherits layer stack from its parent.
2914 if (layer->hasParent()) {
2915 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2916 layer->getName().string());
2917 } else if (idx < 0) {
2918 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2919 "that also does not appear in the top level layer list. Something"
2920 " has gone wrong.", layer->getName().string());
2921 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002922 mCurrentState.layersSortedByZ.removeAt(idx);
2923 mCurrentState.layersSortedByZ.add(layer);
2924 // we need traversal (state changed)
2925 // AND transaction (list changed)
2926 flags |= eTransactionNeeded|eTraversalNeeded;
2927 }
2928 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002929 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002930 if (s.barrierHandle != nullptr) {
2931 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2932 } else if (s.barrierGbp != nullptr) {
2933 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2934 if (authenticateSurfaceTextureLocked(gbp)) {
2935 const auto& otherLayer =
2936 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2937 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2938 } else {
2939 ALOGE("Attempt to defer transaction to to an"
2940 " unrecognized GraphicBufferProducer");
2941 }
2942 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002943 // We don't trigger a traversal here because if no other state is
2944 // changed, we don't want this to cause any more work
2945 }
Robert Carr1db73f62016-12-21 12:58:51 -08002946 if (what & layer_state_t::eReparentChildren) {
2947 if (layer->reparentChildren(s.reparentHandle)) {
2948 flags |= eTransactionNeeded|eTraversalNeeded;
2949 }
2950 }
Robert Carr9524cb32017-02-13 11:32:32 -08002951 if (what & layer_state_t::eDetachChildren) {
2952 layer->detachChildren();
2953 }
Robert Carrc3574f72016-03-24 12:19:32 -07002954 if (what & layer_state_t::eOverrideScalingModeChanged) {
2955 layer->setOverrideScalingMode(s.overrideScalingMode);
2956 // We don't trigger a traversal here because if no other state is
2957 // changed, we don't want this to cause any more work
2958 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002959 }
2960 return flags;
2961}
2962
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002963status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002964 const String8& name,
2965 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002966 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002967 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2968 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002970 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002971 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002972 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002973 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002974 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002975
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002976 status_t result = NO_ERROR;
2977
2978 sp<Layer> layer;
2979
Cody Northropbc755282017-03-31 12:00:08 -06002980 String8 uniqueName = getUniqueLayerName(name);
2981
Mathias Agopian3165cc22012-08-08 19:42:09 -07002982 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2983 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002984 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002985 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002986 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002988 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002989 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002990 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002991 handle, gbp, &layer);
2992 break;
2993 default:
2994 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995 break;
2996 }
2997
Dan Stoza7d89d062015-04-30 13:29:25 -07002998 if (result != NO_ERROR) {
2999 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003001
Albert Chaulk479c60c2017-01-27 14:21:34 -05003002 layer->setInfo(windowType, ownerUid);
3003
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003005 if (result != NO_ERROR) {
3006 return result;
3007 }
Irvelffc9efc2016-07-27 15:16:37 -07003008 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003009
3010 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003011 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012}
3013
Cody Northropbc755282017-03-31 12:00:08 -06003014String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3015{
3016 bool matchFound = true;
3017 uint32_t dupeCounter = 0;
3018
3019 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3020 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3021
3022 // Loop over layers until we're sure there is no matching name
3023 while (matchFound) {
3024 matchFound = false;
3025 mDrawingState.traverseInZOrder([&](Layer* layer) {
3026 if (layer->getName() == uniqueName) {
3027 matchFound = true;
3028 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3029 }
3030 });
3031 }
3032
3033 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3034
3035 return uniqueName;
3036}
3037
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003038status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3039 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3040 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041{
3042 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003043 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044 case PIXEL_FORMAT_TRANSPARENT:
3045 case PIXEL_FORMAT_TRANSLUCENT:
3046 format = PIXEL_FORMAT_RGBA_8888;
3047 break;
3048 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003049 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 break;
3051 }
3052
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003053 *outLayer = new Layer(this, client, name, w, h, flags);
3054 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3055 if (err == NO_ERROR) {
3056 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003057 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003059
3060 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3061 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062}
3063
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003064status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3065 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3066 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003068 *outLayer = new LayerDim(this, client, name, w, h, flags);
3069 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003070 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003071 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003072}
3073
Mathias Agopianac9fa422013-02-11 16:40:36 -08003074status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075{
Robert Carr9524cb32017-02-13 11:32:32 -08003076 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003077 status_t err = NO_ERROR;
3078 sp<Layer> l(client->getLayerUser(handle));
3079 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003080 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003081 err = removeLayer(l);
3082 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3083 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003084 }
3085 return err;
3086}
3087
Mathias Agopian13127d82013-03-05 17:47:11 -08003088status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003089{
Mathias Agopian67106042013-03-14 19:18:13 -07003090 // called by ~LayerCleaner() when all references to the IBinder (handle)
3091 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003092 sp<Layer> l = layer.promote();
3093 if (l == nullptr) {
3094 // The layer has already been removed, carry on
3095 return NO_ERROR;
3096 } if (l->getParent() != nullptr) {
3097 // If we have a parent, then we can continue to live as long as it does.
3098 return NO_ERROR;
3099 }
3100 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101}
3102
Mathias Agopianb60314a2012-04-10 22:09:54 -07003103// ---------------------------------------------------------------------------
3104
Andy McFadden13a082e2012-08-24 10:16:42 -07003105void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003106 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003107 Vector<ComposerState> state;
3108 Vector<DisplayState> displays;
3109 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003110 d.what = DisplayState::eDisplayProjectionChanged |
3111 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003112 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003113 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003114 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003115 d.frame.makeInvalid();
3116 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003117 d.width = 0;
3118 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003119 displays.add(d);
3120 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003121 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003122
Dan Stoza9e56aa02015-11-02 13:00:03 -08003123 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3124 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003125 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003126
Brian Andersond0010582017-03-07 13:20:31 -08003127 // Use phase of 0 since phase is not known.
3128 // Use latency of 0, which will snap to the ideal latency.
3129 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003130}
3131
3132void SurfaceFlinger::initializeDisplays() {
3133 class MessageScreenInitialized : public MessageBase {
3134 SurfaceFlinger* flinger;
3135 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003136 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003137 virtual bool handler() {
3138 flinger->onInitializeDisplays();
3139 return true;
3140 }
3141 };
3142 sp<MessageBase> msg = new MessageScreenInitialized(this);
3143 postMessageAsync(msg); // we may be called from main thread, use async message
3144}
3145
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003146void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3147 int mode) {
3148 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3149 this);
3150 int32_t type = hw->getDisplayType();
3151 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003152
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003153 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003154 return;
3155 }
3156
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003157 hw->setPowerMode(mode);
3158 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3159 ALOGW("Trying to set power mode for virtual display");
3160 return;
3161 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003162
Irvelffc9efc2016-07-27 15:16:37 -07003163 if (mInterceptor.isEnabled()) {
3164 Mutex::Autolock _l(mStateLock);
3165 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3166 if (idx < 0) {
3167 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3168 return;
3169 }
3170 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3171 }
3172
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003173 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003174 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003175 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003176 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3177 // FIXME: eventthread only knows about the main display right now
3178 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003179 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003180 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003182 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003183 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003184 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003185
3186 struct sched_param param = {0};
3187 param.sched_priority = 1;
3188 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3189 ALOGW("Couldn't set SCHED_FIFO on display on");
3190 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003191 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003192 // Turn off the display
3193 struct sched_param param = {0};
3194 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3195 ALOGW("Couldn't set SCHED_OTHER on display off");
3196 }
3197
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003198 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003199 disableHardwareVsync(true); // also cancels any in-progress resync
3200
Mathias Agopiancde87a32012-09-13 14:09:01 -07003201 // FIXME: eventthread only knows about the main display right now
3202 mEventThread->onScreenReleased();
3203 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003204
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003205 getHwComposer().setPowerMode(type, mode);
3206 mVisibleRegionsDirty = true;
3207 // from this point on, SF will stop drawing on this display
3208 } else {
3209 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003210 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003211}
3212
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3214 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003215 SurfaceFlinger& mFlinger;
3216 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003217 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003218 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003219 MessageSetPowerMode(SurfaceFlinger& flinger,
3220 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3221 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003222 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003223 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003224 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003225 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003226 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003227 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003228 ALOGW("Attempt to set power mode = %d for virtual display",
3229 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003230 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003231 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003232 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003233 return true;
3234 }
3235 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003236 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003237 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003238}
3239
3240// ---------------------------------------------------------------------------
3241
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3243{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003245
Mathias Agopianbd115332013-04-18 16:41:04 -07003246 IPCThreadState* ipc = IPCThreadState::self();
3247 const int pid = ipc->getCallingPid();
3248 const int uid = ipc->getCallingUid();
3249 if ((uid != AID_SHELL) &&
3250 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003251 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003252 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003254 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003255 // (this would indicate SF is stuck, but we want to be able to
3256 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003257 status_t err = mStateLock.timedLock(s2ns(1));
3258 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003259 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003260 result.appendFormat(
3261 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3262 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003263 }
3264
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003265 bool dumpAll = true;
3266 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003267 size_t numArgs = args.size();
3268 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003269 if ((index < numArgs) &&
3270 (args[index] == String16("--list"))) {
3271 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003272 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003273 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003274 }
3275
3276 if ((index < numArgs) &&
3277 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003278 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003279 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003280 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003281 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003282
3283 if ((index < numArgs) &&
3284 (args[index] == String16("--latency-clear"))) {
3285 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003286 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003287 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003288 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003289
3290 if ((index < numArgs) &&
3291 (args[index] == String16("--dispsync"))) {
3292 index++;
3293 mPrimaryDispSync.dump(result);
3294 dumpAll = false;
3295 }
Dan Stozab90cf072015-03-05 11:05:59 -08003296
3297 if ((index < numArgs) &&
3298 (args[index] == String16("--static-screen"))) {
3299 index++;
3300 dumpStaticScreenStats(result);
3301 dumpAll = false;
3302 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003303
3304 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003305 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003306 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003307 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003308 dumpAll = false;
3309 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003310
3311 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3312 index++;
3313 dumpWideColorInfo(result);
3314 dumpAll = false;
3315 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003317
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003318 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003319 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003320 }
3321
Mathias Agopian9795c422009-08-26 16:36:26 -07003322 if (locked) {
3323 mStateLock.unlock();
3324 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003325 }
3326 write(fd, result.string(), result.size());
3327 return NO_ERROR;
3328}
3329
Dan Stozac7014012014-02-14 15:03:43 -08003330void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3331 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003332{
Robert Carr2047fae2016-11-28 14:09:09 -08003333 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003334 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003335 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003336}
3337
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003338void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003339 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003340{
3341 String8 name;
3342 if (index < args.size()) {
3343 name = String8(args[index]);
3344 index++;
3345 }
3346
Dan Stoza9e56aa02015-11-02 13:00:03 -08003347 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3348 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003349 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003350
3351 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003352 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003353 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003354 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003355 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003356 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003357 }
Robert Carr2047fae2016-11-28 14:09:09 -08003358 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003359 }
3360}
3361
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003362void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003363 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003364{
3365 String8 name;
3366 if (index < args.size()) {
3367 name = String8(args[index]);
3368 index++;
3369 }
3370
Robert Carr2047fae2016-11-28 14:09:09 -08003371 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003372 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003373 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003374 }
Robert Carr2047fae2016-11-28 14:09:09 -08003375 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003376
Svetoslavd85084b2014-03-20 10:28:31 -07003377 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003378}
3379
Jamie Gennis6547ff42013-07-16 20:12:42 -07003380// This should only be called from the main thread. Otherwise it would need
3381// the lock and should use mCurrentState rather than mDrawingState.
3382void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003383 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003384 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003385 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003386
3387 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3388}
3389
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003390void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003391{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003392 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003393 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3394
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003395 if (isLayerTripleBufferingDisabled())
3396 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003397
3398 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003399 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003400 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003401 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003402 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3403 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003404 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003405}
3406
Dan Stozab90cf072015-03-05 11:05:59 -08003407void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3408{
3409 result.appendFormat("Static screen stats:\n");
3410 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3411 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3412 float percent = 100.0f *
3413 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3414 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3415 b + 1, bucketTimeSec, percent);
3416 }
3417 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3418 float percent = 100.0f *
3419 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3420 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3421 NUM_BUCKETS - 1, bucketTimeSec, percent);
3422}
3423
Dan Stozae77c7662016-05-13 11:37:28 -07003424void SurfaceFlinger::recordBufferingStats(const char* layerName,
3425 std::vector<OccupancyTracker::Segment>&& history) {
3426 Mutex::Autolock lock(mBufferingStatsMutex);
3427 auto& stats = mBufferingStats[layerName];
3428 for (const auto& segment : history) {
3429 if (!segment.usedThirdBuffer) {
3430 stats.twoBufferTime += segment.totalTime;
3431 }
3432 if (segment.occupancyAverage < 1.0f) {
3433 stats.doubleBufferedTime += segment.totalTime;
3434 } else if (segment.occupancyAverage < 2.0f) {
3435 stats.tripleBufferedTime += segment.totalTime;
3436 }
3437 ++stats.numSegments;
3438 stats.totalTime += segment.totalTime;
3439 }
3440}
3441
Brian Andersond6927fb2016-07-23 23:37:30 -07003442void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3443 result.appendFormat("Layer frame timestamps:\n");
3444
3445 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3446 const size_t count = currentLayers.size();
3447 for (size_t i=0 ; i<count ; i++) {
3448 currentLayers[i]->dumpFrameEvents(result);
3449 }
3450}
3451
Dan Stozae77c7662016-05-13 11:37:28 -07003452void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3453 result.append("Buffering stats:\n");
3454 result.append(" [Layer name] <Active time> <Two buffer> "
3455 "<Double buffered> <Triple buffered>\n");
3456 Mutex::Autolock lock(mBufferingStatsMutex);
3457 typedef std::tuple<std::string, float, float, float> BufferTuple;
3458 std::map<float, BufferTuple, std::greater<float>> sorted;
3459 for (const auto& statsPair : mBufferingStats) {
3460 const char* name = statsPair.first.c_str();
3461 const BufferingStats& stats = statsPair.second;
3462 if (stats.numSegments == 0) {
3463 continue;
3464 }
3465 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3466 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3467 stats.totalTime;
3468 float doubleBufferRatio = static_cast<float>(
3469 stats.doubleBufferedTime) / stats.totalTime;
3470 float tripleBufferRatio = static_cast<float>(
3471 stats.tripleBufferedTime) / stats.totalTime;
3472 sorted.insert({activeTime, {name, twoBufferRatio,
3473 doubleBufferRatio, tripleBufferRatio}});
3474 }
3475 for (const auto& sortedPair : sorted) {
3476 float activeTime = sortedPair.first;
3477 const BufferTuple& values = sortedPair.second;
3478 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3479 std::get<0>(values).c_str(), activeTime,
3480 std::get<1>(values), std::get<2>(values),
3481 std::get<3>(values));
3482 }
3483 result.append("\n");
3484}
3485
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003486void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3487 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3488
3489 // TODO: print out if wide-color mode is active or not
3490
3491 for (size_t d = 0; d < mDisplays.size(); d++) {
3492 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3493 int32_t hwcId = displayDevice->getHwcDisplayId();
3494 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3495 continue;
3496 }
3497
3498 result.appendFormat("Display %d color modes:\n", hwcId);
3499 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3500 for (auto&& mode : modes) {
3501 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3502 }
3503
3504 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3505 result.appendFormat(" Current color mode: %s (%d)\n",
3506 decodeColorMode(currentMode).c_str(), currentMode);
3507 }
3508 result.append("\n");
3509}
3510
Mathias Agopian74d211a2013-04-22 16:55:35 +02003511void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3512 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003513{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003514 bool colorize = false;
3515 if (index < args.size()
3516 && (args[index] == String16("--color"))) {
3517 colorize = true;
3518 index++;
3519 }
3520
3521 Colorizer colorizer(colorize);
3522
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003523 // figure out if we're stuck somewhere
3524 const nsecs_t now = systemTime();
3525 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3526 const nsecs_t inTransaction(mDebugInTransaction);
3527 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3528 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3529
3530 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003531 * Dump library configuration.
3532 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003533
3534 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003535 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003536 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003537 appendSfConfigString(result);
3538 appendUiConfigString(result);
3539 appendGuiConfigString(result);
3540 result.append("\n");
3541
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003542 result.append("\nWide-Color information:\n");
3543 dumpWideColorInfo(result);
3544
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003545 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003546 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003547 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003548 result.append(SyncFeatures::getInstance().toString());
3549 result.append("\n");
3550
Dan Stoza9e56aa02015-11-02 13:00:03 -08003551 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3552
Andy McFadden41d67d72014-04-25 16:58:34 -07003553 colorizer.bold(result);
3554 result.append("DispSync configuration: ");
3555 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003556 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003557 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003558 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003559 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003560 result.append("\n");
3561
Dan Stozab90cf072015-03-05 11:05:59 -08003562 // Dump static screen stats
3563 result.append("\n");
3564 dumpStaticScreenStats(result);
3565 result.append("\n");
3566
Dan Stozae77c7662016-05-13 11:37:28 -07003567 dumpBufferingStats(result);
3568
Andy McFadden4803b742012-09-24 19:07:20 -07003569 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003570 * Dump the visible layer list
3571 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003572 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003573 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003574 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003575 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003576 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003577 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578
3579 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003580 * Dump Display state
3581 */
3582
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003583 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003584 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003585 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003586 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3587 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003588 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003589 }
3590
3591 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003592 * Dump SurfaceFlinger global state
3593 */
3594
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003595 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003596 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003597 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003598
Mathias Agopian888c8222012-08-04 21:10:38 -07003599 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003600 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003601
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003602 colorizer.bold(result);
3603 result.appendFormat("EGL implementation : %s\n",
3604 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3605 colorizer.reset(result);
3606 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003607 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003608
Mathias Agopian875d8e12013-06-07 15:35:48 -07003609 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610
Mathias Agopian42977342012-08-05 00:40:46 -07003611 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003612 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3613 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003614 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003615 " last eglSwapBuffers() time: %f us\n"
3616 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003617 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003618 " refresh-rate : %f fps\n"
3619 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003620 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003621 " gpu_to_cpu_unsupported : %d\n"
3622 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003623 mLastSwapBufferTime/1000.0,
3624 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003625 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003626 1e9 / activeConfig->getVsyncPeriod(),
3627 activeConfig->getDpiX(),
3628 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003629 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003630
Mathias Agopian74d211a2013-04-22 16:55:35 +02003631 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003632 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003633
Mathias Agopian74d211a2013-04-22 16:55:35 +02003634 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003635 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003636
3637 /*
3638 * VSYNC state
3639 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003640 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003641 result.append("\n");
3642
3643 /*
3644 * HWC layer minidump
3645 */
3646 for (size_t d = 0; d < mDisplays.size(); d++) {
3647 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3648 int32_t hwcId = displayDevice->getHwcDisplayId();
3649 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3650 continue;
3651 }
3652
3653 result.appendFormat("Display %d HWC layers:\n", hwcId);
3654 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003655 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003656 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003657 });
Dan Stozae22aec72016-08-01 13:20:59 -07003658 result.append("\n");
3659 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003660
3661 /*
3662 * Dump HWComposer state
3663 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003664 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003665 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003666 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003667 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003668 result.appendFormat(" h/w composer %s\n",
3669 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003670 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003671
3672 /*
3673 * Dump gralloc state
3674 */
3675 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3676 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003677}
3678
Mathias Agopian13127d82013-03-05 17:47:11 -08003679const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003680SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003681 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003682 wp<IBinder> dpy;
3683 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3684 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3685 dpy = mDisplays.keyAt(i);
3686 break;
3687 }
3688 }
3689 if (dpy == NULL) {
3690 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3691 // Just use the primary display so we have something to return
3692 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3693 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003694 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003695}
3696
Keun young Park63f165f2012-08-31 10:53:36 -07003697bool SurfaceFlinger::startDdmConnection()
3698{
3699 void* libddmconnection_dso =
3700 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3701 if (!libddmconnection_dso) {
3702 return false;
3703 }
3704 void (*DdmConnection_start)(const char* name);
3705 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003706 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003707 if (!DdmConnection_start) {
3708 dlclose(libddmconnection_dso);
3709 return false;
3710 }
3711 (*DdmConnection_start)(getServiceName());
3712 return true;
3713}
3714
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003715status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 switch (code) {
3717 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003718 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003720 case CLEAR_ANIMATION_FRAME_STATS:
3721 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003723 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724 {
3725 // codes that require permission check
3726 IPCThreadState* ipc = IPCThreadState::self();
3727 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003728 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003729 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003730 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003731 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003732 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003734 break;
3735 }
Robert Carr1db73f62016-12-21 12:58:51 -08003736 /*
3737 * Calling setTransactionState is safe, because you need to have been
3738 * granted a reference to Client* and Handle* to do anything with it.
3739 *
3740 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3741 */
3742 case SET_TRANSACTION_STATE:
3743 case CREATE_SCOPED_CONNECTION:
3744 {
3745 return OK;
3746 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003747 case CAPTURE_SCREEN:
3748 {
3749 // codes that require permission check
3750 IPCThreadState* ipc = IPCThreadState::self();
3751 const int pid = ipc->getCallingPid();
3752 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003753 if ((uid != AID_GRAPHICS) &&
3754 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003755 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003756 return PERMISSION_DENIED;
3757 }
3758 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759 }
3760 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003761 return OK;
3762}
3763
3764status_t SurfaceFlinger::onTransact(
3765 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3766{
3767 status_t credentialCheck = CheckTransactCodeCredentials(code);
3768 if (credentialCheck != OK) {
3769 return credentialCheck;
3770 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003772 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3773 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003774 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003775 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003776 IPCThreadState* ipc = IPCThreadState::self();
3777 const int pid = ipc->getCallingPid();
3778 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003779 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003780 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 return PERMISSION_DENIED;
3782 }
3783 int n;
3784 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003785 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003786 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787 return NO_ERROR;
3788 case 1002: // SHOW_UPDATES
3789 n = data.readInt32();
3790 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003791 invalidateHwcGeometry();
3792 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003794 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003795 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003796 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003797 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003798 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003799 setTransactionFlags(
3800 eTransactionNeeded|
3801 eDisplayTransactionNeeded|
3802 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003803 return NO_ERROR;
3804 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003805 case 1006:{ // send empty update
3806 signalRefresh();
3807 return NO_ERROR;
3808 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003809 case 1008: // toggle use of hw composer
3810 n = data.readInt32();
3811 mDebugDisableHWC = n ? 1 : 0;
3812 invalidateHwcGeometry();
3813 repaintEverything();
3814 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003815 case 1009: // toggle use of transform hint
3816 n = data.readInt32();
3817 mDebugDisableTransformHint = n ? 1 : 0;
3818 invalidateHwcGeometry();
3819 repaintEverything();
3820 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003822 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 reply->writeInt32(0);
3824 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003825 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003826 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 return NO_ERROR;
3828 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003829 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003830 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003831 return NO_ERROR;
3832 }
3833 case 1014: {
3834 // daltonize
3835 n = data.readInt32();
3836 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003837 case 1:
3838 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3839 break;
3840 case 2:
3841 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3842 break;
3843 case 3:
3844 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3845 break;
3846 default:
3847 mDaltonizer.setType(ColorBlindnessType::None);
3848 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003849 }
3850 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003851 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003852 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003853 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003854 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003855 invalidateHwcGeometry();
3856 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003857 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003858 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003859 case 1015: {
3860 // apply a color matrix
3861 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003862 if (n) {
3863 // color matrix is sent as mat3 matrix followed by vec3
3864 // offset, then packed into a mat4 where the last row is
3865 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003866 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003867 for (size_t j = 0; j < 4; j++) {
3868 mColorMatrix[i][j] = data.readFloat();
3869 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003870 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003871 } else {
3872 mColorMatrix = mat4();
3873 }
3874 invalidateHwcGeometry();
3875 repaintEverything();
3876 return NO_ERROR;
3877 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003878 // This is an experimental interface
3879 // Needs to be shifted to proper binder interface when we productize
3880 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003881 n = data.readInt32();
3882 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003883 return NO_ERROR;
3884 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003885 case 1017: {
3886 n = data.readInt32();
3887 mForceFullDamage = static_cast<bool>(n);
3888 return NO_ERROR;
3889 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003890 case 1018: { // Modify Choreographer's phase offset
3891 n = data.readInt32();
3892 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3893 return NO_ERROR;
3894 }
3895 case 1019: { // Modify SurfaceFlinger's phase offset
3896 n = data.readInt32();
3897 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3898 return NO_ERROR;
3899 }
Irvel468051e2016-06-13 16:44:44 -07003900 case 1020: { // Layer updates interceptor
3901 n = data.readInt32();
3902 if (n) {
3903 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003904 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003905 }
3906 else{
3907 ALOGV("Interceptor disabled");
3908 mInterceptor.disable();
3909 }
3910 return NO_ERROR;
3911 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003912 case 1021: { // Disable HWC virtual displays
3913 n = data.readInt32();
3914 mUseHwcVirtualDisplays = !n;
3915 return NO_ERROR;
3916 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 }
3918 }
3919 return err;
3920}
3921
Mathias Agopian53331da2011-08-22 21:44:41 -07003922void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003923 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003924 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003925}
3926
Mathias Agopian59119e62010-10-11 12:37:43 -07003927// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003928// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003929// ---------------------------------------------------------------------------
3930
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003931/* The code below is here to handle b/8734824
3932 *
3933 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003934 * from the surfaceflinger thread to the calling binder thread, where they
3935 * are executed. This allows the calling thread in the calling process to be
3936 * reused and not depend on having "enough" binder threads to handle the
3937 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003938 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003939class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003940 /* Parts of GraphicProducerWrapper are run on two different threads,
3941 * communicating by sending messages via Looper but also by shared member
3942 * data. Coherence maintenance is subtle and in places implicit (ugh).
3943 *
3944 * Don't rely on Looper's sendMessage/handleMessage providing
3945 * release/acquire semantics for any data not actually in the Message.
3946 * Data going from surfaceflinger to binder threads needs to be
3947 * synchronized explicitly.
3948 *
3949 * Barrier open/wait do provide release/acquire semantics. This provides
3950 * implicit synchronization for data coming back from binder to
3951 * surfaceflinger threads.
3952 */
3953
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954 sp<IGraphicBufferProducer> impl;
3955 sp<Looper> looper;
3956 status_t result;
3957 bool exitPending;
3958 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003959 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003960 uint32_t code;
3961 Parcel const* data;
3962 Parcel* reply;
3963
3964 enum {
3965 MSG_API_CALL,
3966 MSG_EXIT
3967 };
3968
3969 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003970 * Called on surfaceflinger thread. This is called by our "fake"
3971 * BpGraphicBufferProducer. We package the data and reply Parcel and
3972 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003973 */
3974 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003975 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003976 this->code = code;
3977 this->data = &data;
3978 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003979 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003980 // if we've exited, we run the message synchronously right here.
3981 // note (JH): as far as I can tell from looking at the code, this
3982 // never actually happens. if it does, i'm not sure if it happens
3983 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003984 handleMessage(Message(MSG_API_CALL));
3985 } else {
3986 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003987 // Prevent stores to this->{code, data, reply} from being
3988 // reordered later than the construction of Message.
3989 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003990 looper->sendMessage(this, Message(MSG_API_CALL));
3991 barrier.wait();
3992 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003993 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003994 }
3995
3996 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003997 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003998 * call the real BpGraphicBufferProducer.
3999 */
4000 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004001 int what = message.what;
4002 // Prevent reads below from happening before the read from Message
4003 atomic_thread_fence(memory_order_acquire);
4004 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004005 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004006 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004007 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004008 exitRequested = true;
4009 }
4010 }
4011
4012public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004013 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004014 : impl(impl),
4015 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004016 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004017 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004018 exitRequested(false),
4019 code(0),
4020 data(NULL),
4021 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004022 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004023
Jesse Hallb154c422014-07-13 12:47:02 -07004024 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004025 status_t waitForResponse() {
4026 do {
4027 looper->pollOnce(-1);
4028 } while (!exitRequested);
4029 return result;
4030 }
4031
Jesse Hallb154c422014-07-13 12:47:02 -07004032 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004033 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004034 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004035 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004036 // Ensure this->result is visible to the binder thread before it
4037 // handles the message.
4038 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004039 looper->sendMessage(this, Message(MSG_EXIT));
4040 }
4041};
4042
4043
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004044status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4045 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004046 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004047 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004048 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004049
4050 if (CC_UNLIKELY(display == 0))
4051 return BAD_VALUE;
4052
4053 if (CC_UNLIKELY(producer == 0))
4054 return BAD_VALUE;
4055
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004056 // if we have secure windows on this display, never allow the screen capture
4057 // unless the producer interface is local (i.e.: we can take a screenshot for
4058 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004059 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004060
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004061 // Convert to surfaceflinger's internal rotation type.
4062 Transform::orientation_flags rotationFlags;
4063 switch (rotation) {
4064 case ISurfaceComposer::eRotateNone:
4065 rotationFlags = Transform::ROT_0;
4066 break;
4067 case ISurfaceComposer::eRotate90:
4068 rotationFlags = Transform::ROT_90;
4069 break;
4070 case ISurfaceComposer::eRotate180:
4071 rotationFlags = Transform::ROT_180;
4072 break;
4073 case ISurfaceComposer::eRotate270:
4074 rotationFlags = Transform::ROT_270;
4075 break;
4076 default:
4077 rotationFlags = Transform::ROT_0;
4078 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4079 break;
4080 }
4081
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004082 class MessageCaptureScreen : public MessageBase {
4083 SurfaceFlinger* flinger;
4084 sp<IBinder> display;
4085 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004086 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004087 uint32_t reqWidth, reqHeight;
4088 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004089 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004090 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004091 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004092 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004093 public:
4094 MessageCaptureScreen(SurfaceFlinger* flinger,
4095 const sp<IBinder>& display,
4096 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004097 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004098 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004099 bool useIdentityTransform,
4100 Transform::orientation_flags rotation,
4101 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004102 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004103 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004104 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004105 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004106 rotation(rotation), result(PERMISSION_DENIED),
4107 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004108 {
4109 }
4110 status_t getResult() const {
4111 return result;
4112 }
4113 virtual bool handler() {
4114 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004115 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004116 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004117 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004118 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004119 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004120 return true;
4121 }
4122 };
4123
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004124 // this creates a "fake" BBinder which will serve as a "fake" remote
4125 // binder to receive the marshaled calls and forward them to the
4126 // real remote (a BpGraphicBufferProducer)
4127 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4128
4129 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4130 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004131 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004132 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004133 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004134 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004135
4136 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004137 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004138 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004139 }
4140 return res;
4141}
4142
Mathias Agopian180f10d2013-04-10 22:55:41 -07004143
4144void SurfaceFlinger::renderScreenImplLocked(
4145 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004146 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004147 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004148 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004149{
4150 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004151 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004152
4153 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004154 const int32_t hw_w = hw->getWidth();
4155 const int32_t hw_h = hw->getHeight();
4156 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004157 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004158
Dan Stozac1879002014-05-22 15:59:05 -07004159 // if a default or invalid sourceCrop is passed in, set reasonable values
4160 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4161 !sourceCrop.isValid()) {
4162 sourceCrop.setLeftTop(Point(0, 0));
4163 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4164 }
4165
4166 // ensure that sourceCrop is inside screen
4167 if (sourceCrop.left < 0) {
4168 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4169 }
Dan Stozabe31f442014-06-11 11:20:54 -07004170 if (sourceCrop.right > hw_w) {
4171 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004172 }
4173 if (sourceCrop.top < 0) {
4174 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4175 }
Dan Stozabe31f442014-06-11 11:20:54 -07004176 if (sourceCrop.bottom > hw_h) {
4177 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004178 }
4179
Mathias Agopian180f10d2013-04-10 22:55:41 -07004180 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004181 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004182
4183 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004184 engine.setViewportAndProjection(
4185 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004186 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004187
4188 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004189 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004190
Robert Carr1f0a16a2016-10-24 16:27:39 -07004191 // We loop through the first level of layers without traversing,
4192 // as we need to interpret min/max layer Z in the top level Z space.
4193 for (const auto& layer : mDrawingState.layersSortedByZ) {
4194 if (layer->getLayerStack() != hw->getLayerStack()) {
4195 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004196 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004197 const Layer::State& state(layer->getDrawingState());
4198 if (state.z < minLayerZ || state.z > maxLayerZ) {
4199 continue;
4200 }
Dan Stoza412903f2017-04-27 13:42:17 -07004201 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004202 if (!layer->isVisible()) {
4203 return;
4204 }
4205 if (filtering) layer->setFiltering(true);
4206 layer->draw(hw, useIdentityTransform);
4207 if (filtering) layer->setFiltering(false);
4208 });
4209 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004210
Mathias Agopian931bda12013-08-28 18:11:46 -07004211 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004212}
4213
4214
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004215status_t SurfaceFlinger::captureScreenImplLocked(
4216 const sp<const DisplayDevice>& hw,
4217 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004218 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004219 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004220 bool useIdentityTransform, Transform::orientation_flags rotation,
4221 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004222{
4223 ATRACE_CALL();
4224
Mathias Agopian180f10d2013-04-10 22:55:41 -07004225 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004226 uint32_t hw_w = hw->getWidth();
4227 uint32_t hw_h = hw->getHeight();
4228
4229 if (rotation & Transform::ROT_90) {
4230 std::swap(hw_w, hw_h);
4231 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004232
Mathias Agopian180f10d2013-04-10 22:55:41 -07004233 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4234 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4235 reqWidth, reqHeight, hw_w, hw_h);
4236 return BAD_VALUE;
4237 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004238
Mathias Agopian180f10d2013-04-10 22:55:41 -07004239 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4240 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4241
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004242 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004243 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004244 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004245 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4246 (state.z < minLayerZ || state.z > maxLayerZ)) {
4247 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004248 }
Dan Stoza412903f2017-04-27 13:42:17 -07004249 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004250 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4251 layer->isSecure());
4252 });
4253 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004254
4255 if (!isLocalScreenshot && secureLayerIsVisible) {
4256 ALOGW("FB is protected: PERMISSION_DENIED");
4257 return PERMISSION_DENIED;
4258 }
4259
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004260 // create a surface (because we're a producer, and we need to
4261 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004262 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004263
4264 // Put the screenshot Surface into async mode so that
4265 // Layer::headFenceHasSignaled will always return true and we'll latch the
4266 // first buffer regardless of whether or not its acquire fence has
4267 // signaled. This is needed to avoid a race condition in the rotation
4268 // animation. See b/30209608
4269 sur->setAsyncMode(true);
4270
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004271 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004272
Michael Lentine5a16a622015-05-21 13:48:24 -07004273 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4274 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004275 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4276 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004277
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004278 int err = 0;
4279 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004280 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004281 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4282 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004283
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004284 if (err == NO_ERROR) {
4285 ANativeWindowBuffer* buffer;
4286 /* TODO: Once we have the sync framework everywhere this can use
4287 * server-side waits on the fence that dequeueBuffer returns.
4288 */
4289 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4290 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004291 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004292 // create an EGLImage from the buffer so we can later
4293 // turn it into a texture
4294 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4295 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4296 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004297 // this binds the given EGLImage as a framebuffer for the
4298 // duration of this scope.
4299 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4300 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004301 // this will in fact render into our dequeued buffer
4302 // via an FBO, which means we didn't have to create
4303 // an EGLSurface and therefore we're not
4304 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004305 renderScreenImplLocked(
4306 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4307 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004308
Riley Andrews86639902014-08-15 12:27:24 -07004309 // Attempt to create a sync khr object that can produce a sync point. If that
4310 // isn't available, create a non-dupable sync object in the fallback path and
4311 // wait on it directly.
4312 EGLSyncKHR sync;
4313 if (!DEBUG_SCREENSHOTS) {
4314 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004315 // native fence fd will not be populated until flush() is done.
4316 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004317 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004318 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004319 }
Riley Andrews86639902014-08-15 12:27:24 -07004320 if (sync != EGL_NO_SYNC_KHR) {
4321 // get the sync fd
4322 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4323 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4324 ALOGW("captureScreen: failed to dup sync khr object");
4325 syncFd = -1;
4326 }
4327 eglDestroySyncKHR(mEGLDisplay, sync);
4328 } else {
4329 // fallback path
4330 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4331 if (sync != EGL_NO_SYNC_KHR) {
4332 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4333 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4334 EGLint eglErr = eglGetError();
4335 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4336 ALOGW("captureScreen: fence wait timed out");
4337 } else {
4338 ALOGW_IF(eglErr != EGL_SUCCESS,
4339 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4340 }
4341 eglDestroySyncKHR(mEGLDisplay, sync);
4342 } else {
4343 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4344 }
4345 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004346 if (DEBUG_SCREENSHOTS) {
4347 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4348 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4349 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4350 hw, minLayerZ, maxLayerZ);
4351 delete [] pixels;
4352 }
4353
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004354 } else {
4355 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4356 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004357 window->cancelBuffer(window, buffer, syncFd);
4358 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004359 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004360 // destroy our image
4361 eglDestroyImageKHR(mEGLDisplay, image);
4362 } else {
4363 result = BAD_VALUE;
4364 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004365 if (buffer) {
4366 // queueBuffer takes ownership of syncFd
4367 result = window->queueBuffer(window, buffer, syncFd);
4368 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004369 }
4370 } else {
4371 result = BAD_VALUE;
4372 }
4373 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4374 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004375
Mathias Agopian74c40c02010-09-29 13:02:36 -07004376 return result;
4377}
4378
Mathias Agopiand5556842013-09-19 17:08:37 -07004379void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004380 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004381 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004382 for (size_t y=0 ; y<h ; y++) {
4383 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4384 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004385 if (p[x] != 0xFF000000) return;
4386 }
4387 }
4388 ALOGE("*** we just took a black screenshot ***\n"
4389 "requested minz=%d, maxz=%d, layerStack=%d",
4390 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004391
Robert Carr2047fae2016-11-28 14:09:09 -08004392 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004393 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004394 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004395 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4396 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004397 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004398 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4399 layer->isVisible() ? '+' : '-',
4400 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004401 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004402 i++;
4403 });
4404 }
4405 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004406 }
4407}
4408
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004409// ---------------------------------------------------------------------------
4410
Dan Stoza412903f2017-04-27 13:42:17 -07004411void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4412 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004413}
4414
Dan Stoza412903f2017-04-27 13:42:17 -07004415void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4416 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004417}
4418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004419}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004420
4421
4422#if defined(__gl_h_)
4423#error "don't include gl/gl.h in this file"
4424#endif
4425
4426#if defined(__gl2_h_)
4427#error "don't include gl2/gl2.h in this file"
4428#endif