blob: 505e81c8e397af93d94ee39541979e14d4a99104 [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) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700587 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800588 mVrFlingerRequestsDisplay = requestDisplay;
589 signalTransaction();
590 };
591 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
592 vrFlingerRequestDisplayCallback);
593 if (!mVrFlinger) {
594 ALOGE("Failed to start vrflinger");
595 }
596 }
597
Mathias Agopian875d8e12013-06-07 15:35:48 -0700598 // retrieve the EGL context that was selected/created
599 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700600
Mathias Agopianda27af92012-09-13 18:17:13 -0700601 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
602 "couldn't create EGLContext");
603
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604 // make the GLContext current so that we can create textures when creating
605 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700606 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700607
Jamie Gennisd1700752013-10-14 12:22:52 -0700608 mEventControlThread = new EventControlThread(this);
609 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
610
Mathias Agopian92a979a2012-08-02 18:32:23 -0700611 // initialize our drawing state
612 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700613
Andy McFadden13a082e2012-08-24 10:16:42 -0700614 // set initial conditions (e.g. unblank default device)
615 initializeDisplays();
616
Dan Stoza4e637772016-07-28 13:31:51 -0700617 mRenderEngine->primeCache();
618
Wei Wangb254fa32017-01-31 17:43:23 -0800619 mStartBootAnimThread = new StartBootAnimThread();
620 if (mStartBootAnimThread->Start() != NO_ERROR) {
621 ALOGE("Run StartBootAnimThread failed!");
622 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800623
Dan Stoza9e56aa02015-11-02 13:00:03 -0800624 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700625}
626
Mathias Agopiana67e4182012-06-19 17:26:12 -0700627void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800628 // Start boot animation service by setting a property mailbox
629 // if property setting thread is already running, Start() will be just a NOP
630 mStartBootAnimThread->Start();
631 // Wait until property was set
632 if (mStartBootAnimThread->join() != NO_ERROR) {
633 ALOGE("Join StartBootAnimThread failed!");
634 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700635}
636
Mathias Agopian875d8e12013-06-07 15:35:48 -0700637size_t SurfaceFlinger::getMaxTextureSize() const {
638 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700639}
640
Mathias Agopian875d8e12013-06-07 15:35:48 -0700641size_t SurfaceFlinger::getMaxViewportDims() const {
642 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700643}
644
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800646
Jamie Gennis582270d2011-08-17 18:19:00 -0700647bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800648 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800649 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800650 return authenticateSurfaceTextureLocked(bufferProducer);
651}
652
653bool SurfaceFlinger::authenticateSurfaceTextureLocked(
654 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800655 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700656 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800657}
658
Brian Anderson6b376712017-04-04 10:51:39 -0700659status_t SurfaceFlinger::getSupportedFrameTimestamps(
660 std::vector<FrameEvent>* outSupported) const {
661 *outSupported = {
662 FrameEvent::REQUESTED_PRESENT,
663 FrameEvent::ACQUIRE,
664 FrameEvent::LATCH,
665 FrameEvent::FIRST_REFRESH_START,
666 FrameEvent::LAST_REFRESH_START,
667 FrameEvent::GPU_COMPOSITION_DONE,
668 FrameEvent::DEQUEUE_READY,
669 FrameEvent::RELEASE,
670 };
671 if (!getHwComposer().hasCapability(
672 HWC2::Capability::PresentFenceIsNotReliable)) {
673 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
674 }
675 return NO_ERROR;
676}
677
Dan Stoza7f7da322014-05-02 15:26:25 -0700678status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
679 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700680 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700681 return BAD_VALUE;
682 }
683
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500684 if (!display.get())
685 return NAME_NOT_FOUND;
686
Jesse Hall692c7232012-11-08 15:41:56 -0800687 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700688 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800689 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700690 type = i;
691 break;
692 }
693 }
694
695 if (type < 0) {
696 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700697 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700698
Mathias Agopian8b736f12012-08-13 17:54:26 -0700699 // TODO: Not sure if display density should handled by SF any longer
700 class Density {
701 static int getDensityFromProperty(char const* propName) {
702 char property[PROPERTY_VALUE_MAX];
703 int density = 0;
704 if (property_get(propName, property, NULL) > 0) {
705 density = atoi(property);
706 }
707 return density;
708 }
709 public:
710 static int getEmuDensity() {
711 return getDensityFromProperty("qemu.sf.lcd_density"); }
712 static int getBuildDensity() {
713 return getDensityFromProperty("ro.sf.lcd_density"); }
714 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700715
Dan Stoza7f7da322014-05-02 15:26:25 -0700716 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700717
Dan Stoza9e56aa02015-11-02 13:00:03 -0800718 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 DisplayInfo info = DisplayInfo();
720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 float xdpi = hwConfig->getDpiX();
722 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700723
724 if (type == DisplayDevice::DISPLAY_PRIMARY) {
725 // The density of the device is provided by a build property
726 float density = Density::getBuildDensity() / 160.0f;
727 if (density == 0) {
728 // the build doesn't provide a density -- this is wrong!
729 // use xdpi instead
730 ALOGE("ro.sf.lcd_density must be defined as a build property");
731 density = xdpi / 160.0f;
732 }
733 if (Density::getEmuDensity()) {
734 // if "qemu.sf.lcd_density" is specified, it overrides everything
735 xdpi = ydpi = density = Density::getEmuDensity();
736 density /= 160.0f;
737 }
738 info.density = density;
739
740 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000741 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
742 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 } else {
744 // TODO: where should this value come from?
745 static const int TV_DENSITY = 213;
746 info.density = TV_DENSITY / 160.0f;
747 info.orientation = 0;
748 }
749
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 info.w = hwConfig->getWidth();
751 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 info.xdpi = xdpi;
753 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900755 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756
Andy McFadden91b2ca82014-06-13 14:04:23 -0700757 // This is how far in advance a buffer must be queued for
758 // presentation at a given time. If you want a buffer to appear
759 // on the screen at time N, you must submit the buffer before
760 // (N - presentationDeadline).
761 //
762 // Normally it's one full refresh period (to give SF a chance to
763 // latch the buffer), but this can be reduced by configuring a
764 // DispSync offset. Any additional delays introduced by the hardware
765 // composer or panel must be accounted for here.
766 //
767 // We add an additional 1ms to allow for processing time and
768 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800770 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700771
772 // All non-virtual displays are currently considered secure.
773 info.secure = true;
774
Michael Wright28f24d02016-07-12 13:30:53 -0700775 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700776 }
777
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 return NO_ERROR;
779}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700780
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800781status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700782 DisplayStatInfo* stats) {
783 if (stats == NULL) {
784 return BAD_VALUE;
785 }
786
787 // FIXME for now we always return stats for the primary display
788 memset(stats, 0, sizeof(*stats));
789 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
790 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
791 return NO_ERROR;
792}
793
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700794int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800795 if (display == NULL) {
796 ALOGE("%s : display is NULL", __func__);
797 return BAD_VALUE;
798 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700799
800 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700801 if (device != NULL) {
802 return device->getActiveConfig();
803 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700804
Dan Stoza24a42e92015-03-09 10:04:11 -0700805 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700806}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700807
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700808void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
809 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
810 this);
811 int32_t type = hw->getDisplayType();
812 int currentMode = hw->getActiveConfig();
813
814 if (mode == currentMode) {
815 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
816 return;
817 }
818
819 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
820 ALOGW("Trying to set config for virtual display");
821 return;
822 }
823
824 hw->setActiveConfig(mode);
825 getHwComposer().setActiveConfig(type, mode);
826}
827
828status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
829 class MessageSetActiveConfig: public MessageBase {
830 SurfaceFlinger& mFlinger;
831 sp<IBinder> mDisplay;
832 int mMode;
833 public:
834 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
835 int mode) :
836 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
837 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700838 Vector<DisplayInfo> configs;
839 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700840 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700841 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700842 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700843 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700844 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700845 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
846 if (hw == NULL) {
847 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700848 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700849 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
850 ALOGW("Attempt to set active config = %d for virtual display",
851 mMode);
852 } else {
853 mFlinger.setActiveConfigInternal(hw, mMode);
854 }
855 return true;
856 }
857 };
858 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
859 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700860 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700861}
Michael Wright28f24d02016-07-12 13:30:53 -0700862status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
863 Vector<android_color_mode_t>* outColorModes) {
864 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
865 return BAD_VALUE;
866 }
867
868 if (!display.get()) {
869 return NAME_NOT_FOUND;
870 }
871
872 int32_t type = NAME_NOT_FOUND;
873 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
874 if (display == mBuiltinDisplays[i]) {
875 type = i;
876 break;
877 }
878 }
879
880 if (type < 0) {
881 return type;
882 }
883
884 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
885 outColorModes->clear();
886 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
887
888 return NO_ERROR;
889}
890
891android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700892 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700893 if (device != nullptr) {
894 return device->getActiveColorMode();
895 }
896 return static_cast<android_color_mode_t>(BAD_VALUE);
897}
898
899void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
900 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700901 int32_t type = hw->getDisplayType();
902 android_color_mode_t currentMode = hw->getActiveColorMode();
903
904 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700905 return;
906 }
907
908 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
909 ALOGW("Trying to set config for virtual display");
910 return;
911 }
912
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600913 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
914 hw->getDisplayType());
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 hw->setActiveColorMode(mode);
917 getHwComposer().setActiveColorMode(type, mode);
918}
919
920
921status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
922 android_color_mode_t colorMode) {
923 class MessageSetActiveColorMode: public MessageBase {
924 SurfaceFlinger& mFlinger;
925 sp<IBinder> mDisplay;
926 android_color_mode_t mMode;
927 public:
928 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
929 android_color_mode_t mode) :
930 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
931 virtual bool handler() {
932 Vector<android_color_mode_t> modes;
933 mFlinger.getDisplayColorModes(mDisplay, &modes);
934 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
935 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600936 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
937 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700938 return true;
939 }
940 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
941 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600942 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
943 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700944 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600945 ALOGW("Attempt to set active color mode %s %d for virtual display",
946 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700947 } else {
948 mFlinger.setActiveColorModeInternal(hw, mMode);
949 }
950 return true;
951 }
952 };
953 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
954 postMessageSync(msg);
955 return NO_ERROR;
956}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700957
Svetoslavd85084b2014-03-20 10:28:31 -0700958status_t SurfaceFlinger::clearAnimationFrameStats() {
959 Mutex::Autolock _l(mStateLock);
960 mAnimFrameTracker.clearStats();
961 return NO_ERROR;
962}
963
964status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
965 Mutex::Autolock _l(mStateLock);
966 mAnimFrameTracker.getStats(outStats);
967 return NO_ERROR;
968}
969
Dan Stozac4f471e2016-03-24 09:31:08 -0700970status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
971 HdrCapabilities* outCapabilities) const {
972 Mutex::Autolock _l(mStateLock);
973
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700974 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700975 if (displayDevice == nullptr) {
976 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
977 return BAD_VALUE;
978 }
979
980 std::unique_ptr<HdrCapabilities> capabilities =
981 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
982 if (capabilities) {
983 std::swap(*outCapabilities, *capabilities);
984 } else {
985 return BAD_VALUE;
986 }
987
988 return NO_ERROR;
989}
990
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700991status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
992 if (enable == mInjectVSyncs) {
993 return NO_ERROR;
994 }
995
996 if (enable) {
997 mInjectVSyncs = enable;
998 ALOGV("VSync Injections enabled");
999 if (mVSyncInjector.get() == nullptr) {
1000 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001001 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001002 }
1003 mEventQueue.setEventThread(mInjectorEventThread);
1004 } else {
1005 mInjectVSyncs = enable;
1006 ALOGV("VSync Injections disabled");
1007 mEventQueue.setEventThread(mSFEventThread);
1008 mVSyncInjector.clear();
1009 }
1010 return NO_ERROR;
1011}
1012
1013status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1014 if (!mInjectVSyncs) {
1015 ALOGE("VSync Injections not enabled");
1016 return BAD_VALUE;
1017 }
1018 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1019 ALOGV("Injecting VSync inside SurfaceFlinger");
1020 mVSyncInjector->onInjectSyncEvent(when);
1021 }
1022 return NO_ERROR;
1023}
1024
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001025// ----------------------------------------------------------------------------
1026
1027sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001028 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001029}
1030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001032
1033void SurfaceFlinger::waitForEvent() {
1034 mEventQueue.waitMessage();
1035}
1036
1037void SurfaceFlinger::signalTransaction() {
1038 mEventQueue.invalidate();
1039}
1040
1041void SurfaceFlinger::signalLayerUpdate() {
1042 mEventQueue.invalidate();
1043}
1044
1045void SurfaceFlinger::signalRefresh() {
1046 mEventQueue.refresh();
1047}
1048
1049status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001050 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001051 return mEventQueue.postMessage(msg, reltime);
1052}
1053
1054status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001055 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001056 status_t res = mEventQueue.postMessage(msg, reltime);
1057 if (res == NO_ERROR) {
1058 msg->wait();
1059 }
1060 return res;
1061}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001063void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001064 do {
1065 waitForEvent();
1066 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067}
1068
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069void SurfaceFlinger::enableHardwareVsync() {
1070 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001071 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001073 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1074 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001076 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077}
1078
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 Mutex::Autolock _l(mHWVsyncLock);
1081
Jesse Hall948fe0c2013-10-14 12:56:09 -07001082 if (makeAvailable) {
1083 mHWVsyncAvailable = true;
1084 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001085 // Hardware vsync is not currently available, so abort the resync
1086 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087 return;
1088 }
1089
Dan Stoza9e56aa02015-11-02 13:00:03 -08001090 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1091 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092
1093 mPrimaryDispSync.reset();
1094 mPrimaryDispSync.setPeriod(period);
1095
1096 if (!mPrimaryHWVsyncEnabled) {
1097 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001098 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1099 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100 mPrimaryHWVsyncEnabled = true;
1101 }
1102}
1103
Jesse Hall948fe0c2013-10-14 12:56:09 -07001104void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105 Mutex::Autolock _l(mHWVsyncLock);
1106 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1108 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 mPrimaryDispSync.endResync();
1110 mPrimaryHWVsyncEnabled = false;
1111 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001112 if (makeUnavailable) {
1113 mHWVsyncAvailable = false;
1114 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115}
1116
Tim Murray4a4e4a22016-04-19 16:29:23 +00001117void SurfaceFlinger::resyncWithRateLimit() {
1118 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1119 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001120 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001121 }
1122}
1123
Steven Thomas3cfac282017-02-06 12:29:30 -08001124void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1125 nsecs_t timestamp) {
1126 Mutex::Autolock lock(mStateLock);
1127 // Ignore any vsyncs from the non-active hardware composer.
1128 if (composer != mHwc) {
1129 return;
1130 }
1131
Jamie Gennisd1700752013-10-14 12:22:52 -07001132 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001133
Jamie Gennisd1700752013-10-14 12:22:52 -07001134 { // Scope for the lock
1135 Mutex::Autolock _l(mHWVsyncLock);
1136 if (type == 0 && mPrimaryHWVsyncEnabled) {
1137 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001138 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001139 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001140
1141 if (needsHwVsync) {
1142 enableHardwareVsync();
1143 } else {
1144 disableHardwareVsync(false);
1145 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001146}
1147
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001148void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001149 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001150 *compositorTiming = mCompositorTiming;
1151}
1152
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001153void SurfaceFlinger::createDefaultDisplayDevice() {
1154 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1155 wp<IBinder> token = mBuiltinDisplays[type];
1156
1157 // All non-virtual displays are currently considered secure.
1158 const bool isSecure = true;
1159
1160 sp<IGraphicBufferProducer> producer;
1161 sp<IGraphicBufferConsumer> consumer;
1162 BufferQueue::createBufferQueue(&producer, &consumer);
1163
1164 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1165
1166 bool hasWideColorModes = false;
1167 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1168 for (android_color_mode_t colorMode : modes) {
1169 switch (colorMode) {
1170 case HAL_COLOR_MODE_DISPLAY_P3:
1171 case HAL_COLOR_MODE_ADOBE_RGB:
1172 case HAL_COLOR_MODE_DCI_P3:
1173 hasWideColorModes = true;
1174 break;
1175 default:
1176 break;
1177 }
1178 }
1179 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1180 token, fbs, producer, mRenderEngine->getEGLConfig(),
1181 hasWideColorModes && hasWideColorDisplay);
1182 mDisplays.add(token, hw);
1183 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1184 if (hasWideColorModes && hasWideColorDisplay) {
1185 defaultColorMode = HAL_COLOR_MODE_SRGB;
1186 }
1187 setActiveColorModeInternal(hw, defaultColorMode);
1188}
1189
1190void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001191 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001192
1193 if (composer->isUsingVrComposer()) {
1194 // We handle initializing the primary display device for the VR
1195 // window manager hwc explicitly at the time of transition.
1196 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1197 ALOGE("External displays are not supported by the vr hardware composer.");
1198 }
1199 return;
1200 }
1201
Dan Stoza9e56aa02015-11-02 13:00:03 -08001202 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1203 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001204 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1205 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001206 } else {
1207 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001208 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001209 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001210 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001211 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001212 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1213 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001214 }
1215 setTransactionFlags(eDisplayTransactionNeeded);
1216
Andy McFadden9e9689c2012-10-10 18:17:51 -07001217 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001218 }
Mathias Agopian86303202012-07-24 22:46:10 -07001219}
1220
Steven Thomas3cfac282017-02-06 12:29:30 -08001221void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1222 Mutex::Autolock lock(mStateLock);
1223 if (composer == mHwc) {
1224 repaintEverything();
1225 } else {
1226 // This isn't from our current hardware composer. If it's a callback
1227 // from the real composer, forward the refresh request to vr
1228 // flinger. Otherwise ignore it.
1229 if (!composer->isUsingVrComposer()) {
1230 mVrFlinger->OnHardwareComposerRefresh();
1231 }
1232 }
1233}
1234
Dan Stoza9e56aa02015-11-02 13:00:03 -08001235void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001236 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 getHwComposer().setVsyncEnabled(disp,
1238 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001239}
1240
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001241void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1242 for (size_t i = 0; i < layers.size(); ++i) {
1243 layers[i]->clearHwcLayers();
1244 }
1245}
1246
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001247// Note: it is assumed the caller holds |mStateLock| when this is called
1248void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001249 disableHardwareVsync(true);
1250 clearHwcLayers(mDrawingState.layersSortedByZ);
1251 clearHwcLayers(mCurrentState.layersSortedByZ);
1252 // Clear the drawing state so that the logic inside of
1253 // handleTransactionLocked will fire. It will determine the delta between
1254 // mCurrentState and mDrawingState and re-apply all changes when we make the
1255 // transition.
1256 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001257 // Release virtual display hwcId during vr mode transition.
1258 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1259 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1260 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1261 displayDevice->disconnect(getHwComposer());
1262 }
1263 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001264 mDisplays.clear();
1265}
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
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001311 // Reset the timing values to account for the period of the swapped in HWC
1312 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1313 const nsecs_t period = activeConfig->getVsyncPeriod();
1314 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1315 setCompositorTimingSnapped(0, period, 0);
1316
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317 android_atomic_or(1, &mRepaintEverything);
1318 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001319}
1320
Mathias Agopian4fec8732012-06-29 14:12:52 -07001321void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001322 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001323 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001324 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001325 bool frameMissed = !mHadClientComposition &&
1326 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001327 (mPreviousPresentFence->getSignalTime() ==
1328 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001329 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001330 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001331 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001332 signalLayerUpdate();
1333 break;
1334 }
1335
Steven Thomas050b2c82017-03-06 11:45:16 -08001336 // Now that we're going to make it to the handleMessageTransaction()
1337 // call below it's safe to call updateVrFlinger(), which will
1338 // potentially trigger a display handoff.
1339 updateVrFlinger();
1340
Dan Stoza6b9454d2014-11-07 16:00:59 -08001341 bool refreshNeeded = handleMessageTransaction();
1342 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001343 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001344 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001345 // Signal a refresh if a transaction modified the window state,
1346 // a new buffer was latched, or if HWC has requested a full
1347 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001348 signalRefresh();
1349 }
1350 break;
1351 }
1352 case MessageQueue::REFRESH: {
1353 handleMessageRefresh();
1354 break;
1355 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001356 }
1357}
1358
Dan Stoza6b9454d2014-11-07 16:00:59 -08001359bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001360 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001361 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001362 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001363 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001364 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001365 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001366}
1367
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001369 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001370 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001371}
1372
1373void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001374 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001375
Pablo Ceballos40845df2016-01-25 17:41:15 -08001376 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001377
Brian Andersond6927fb2016-07-23 23:37:30 -07001378 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001379 rebuildLayerStacks();
1380 setUpHWComposer();
1381 doDebugFlashRegions();
1382 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001383 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001384
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001385 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001386
1387 mHadClientComposition = false;
1388 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1389 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1390 mHadClientComposition = mHadClientComposition ||
1391 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1392 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001395}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001396
Mathias Agopiancd60f992012-08-16 16:28:27 -07001397void SurfaceFlinger::doDebugFlashRegions()
1398{
1399 // is debugging enabled
1400 if (CC_LIKELY(!mDebugRegion))
1401 return;
1402
1403 const bool repaintEverything = mRepaintEverything;
1404 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1405 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001406 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001407 // transform the dirty region into this screen's coordinate space
1408 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1409 if (!dirtyRegion.isEmpty()) {
1410 // redraw the whole screen
1411 doComposeSurfaces(hw, Region(hw->bounds()));
1412
1413 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001415 RenderEngine& engine(getRenderEngine());
1416 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1417
Mathias Agopianda27af92012-09-13 18:17:13 -07001418 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419 }
1420 }
1421 }
1422
1423 postFramebuffer();
1424
1425 if (mDebugRegion > 1) {
1426 usleep(mDebugRegion * 1000);
1427 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001428
Dan Stoza9e56aa02015-11-02 13:00:03 -08001429 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001430 auto& displayDevice = mDisplays[displayId];
1431 if (!displayDevice->isDisplayOn()) {
1432 continue;
1433 }
1434
1435 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001436 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1437 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001438 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439}
1440
Brian Andersond6927fb2016-07-23 23:37:30 -07001441void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001443 ATRACE_CALL();
1444 ALOGV("preComposition");
1445
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001447 mDrawingState.traverseInZOrder([&](Layer* layer) {
1448 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449 needExtraInvalidate = true;
1450 }
Robert Carr2047fae2016-11-28 14:09:09 -08001451 });
1452
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453 if (needExtraInvalidate) {
1454 signalLayerUpdate();
1455 }
1456}
1457
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458void SurfaceFlinger::updateCompositorTiming(
1459 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1460 std::shared_ptr<FenceTime>& presentFenceTime) {
1461 // Update queue of past composite+present times and determine the
1462 // most recently known composite to present latency.
1463 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1464 nsecs_t compositeToPresentLatency = -1;
1465 while (!mCompositePresentTimes.empty()) {
1466 CompositePresentTime& cpt = mCompositePresentTimes.front();
1467 // Cached values should have been updated before calling this method,
1468 // which helps avoid duplicate syscalls.
1469 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1470 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1471 break;
1472 }
1473 compositeToPresentLatency = displayTime - cpt.composite;
1474 mCompositePresentTimes.pop();
1475 }
1476
1477 // Don't let mCompositePresentTimes grow unbounded, just in case.
1478 while (mCompositePresentTimes.size() > 16) {
1479 mCompositePresentTimes.pop();
1480 }
1481
Brian Andersond0010582017-03-07 13:20:31 -08001482 setCompositorTimingSnapped(
1483 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1484}
1485
1486void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1487 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001488 // Integer division and modulo round toward 0 not -inf, so we need to
1489 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001490 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001491 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1492 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1493
Brian Andersond0010582017-03-07 13:20:31 -08001494 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1495 if (idealLatency <= 0) {
1496 idealLatency = vsyncInterval;
1497 }
1498
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499 // Snap the latency to a value that removes scheduling jitter from the
1500 // composition and present times, which often have >1ms of jitter.
1501 // Reducing jitter is important if an app attempts to extrapolate
1502 // something (such as user input) to an accurate diasplay time.
1503 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1504 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001505 nsecs_t bias = vsyncInterval / 2;
1506 int64_t extraVsyncs =
1507 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1508 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1509 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510
Brian Andersond0010582017-03-07 13:20:31 -08001511 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001512 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1513 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001514 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515}
1516
1517void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001518{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001519 ATRACE_CALL();
1520 ALOGV("postComposition");
1521
Brian Anderson3546a3f2016-07-14 11:51:14 -07001522 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001523 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001524 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001525 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001526 }
1527
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001528 // |mStateLock| not needed as we are on the main thread
1529 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001530
1531 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1532 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1533 glCompositionDoneFenceTime =
1534 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1535 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1536 } else {
1537 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1538 }
1539 mGlCompositionDoneTimeline.updateSignalTimes();
1540
Brian Anderson4e606e32017-03-16 15:34:57 -07001541 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1542 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1543 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001544 mDisplayTimeline.updateSignalTimes();
1545
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1547 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1548
1549 // We use the refreshStartTime which might be sampled a little later than
1550 // when we started doing work for this frame, but that should be okay
1551 // since updateCompositorTiming has snapping logic.
1552 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001553 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001554 CompositorTiming compositorTiming;
1555 {
1556 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1557 compositorTiming = mCompositorTiming;
1558 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001559
Robert Carr2047fae2016-11-28 14:09:09 -08001560 mDrawingState.traverseInZOrder([&](Layer* layer) {
1561 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001562 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001563 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001564 recordBufferingStats(layer->getName().string(),
1565 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001566 }
Robert Carr2047fae2016-11-28 14:09:09 -08001567 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001568
Brian Anderson4e606e32017-03-16 15:34:57 -07001569 if (presentFence->isValid()) {
1570 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001571 enableHardwareVsync();
1572 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001573 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001574 }
1575 }
1576
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001577 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001578 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001579 enableHardwareVsync();
1580 }
1581 }
1582
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001583 if (mAnimCompositionPending) {
1584 mAnimCompositionPending = false;
1585
Brian Anderson4e606e32017-03-16 15:34:57 -07001586 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001587 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001588 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001589 } else {
1590 // The HWC doesn't support present fences, so use the refresh
1591 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001592 nsecs_t presentTime =
1593 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001594 mAnimFrameTracker.setActualPresentTime(presentTime);
1595 }
1596 mAnimFrameTracker.advanceFrame();
1597 }
Dan Stozab90cf072015-03-05 11:05:59 -08001598
1599 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1600 return;
1601 }
1602
1603 nsecs_t currentTime = systemTime();
1604 if (mHasPoweredOff) {
1605 mHasPoweredOff = false;
1606 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001607 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001609 if (numPeriods < NUM_BUCKETS - 1) {
1610 mFrameBuckets[numPeriods] += elapsedTime;
1611 } else {
1612 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1613 }
1614 mTotalTime += elapsedTime;
1615 }
1616 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617}
1618
1619void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001620 ATRACE_CALL();
1621 ALOGV("rebuildLayerStacks");
1622
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001624 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1625 ATRACE_CALL();
1626 mVisibleRegionsDirty = false;
1627 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001628
Jeff Sharkey76488112017-02-27 14:15:18 -07001629 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1630 Region opaqueRegion;
1631 Region dirtyRegion;
1632 Vector<sp<Layer>> layersSortedByZ;
1633 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1634 const Transform& tr(displayDevice->getTransform());
1635 const Rect bounds(displayDevice->getBounds());
1636 if (displayDevice->isDisplayOn()) {
1637 computeVisibleRegions(
1638 displayDevice->getLayerStack(), dirtyRegion,
1639 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001640
Jeff Sharkey76488112017-02-27 14:15:18 -07001641 mDrawingState.traverseInZOrder([&](Layer* layer) {
1642 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1643 Region drawRegion(tr.transform(
1644 layer->visibleNonTransparentRegion));
1645 drawRegion.andSelf(bounds);
1646 if (!drawRegion.isEmpty()) {
1647 layersSortedByZ.add(layer);
1648 } else {
1649 // Clear out the HWC layer if this layer was
1650 // previously visible, but no longer is
1651 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1652 nullptr);
1653 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001654 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001655 // WM changes displayDevice->layerStack upon sleep/awake.
1656 // Here we make sure we delete the HWC layers even if
1657 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001658 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1659 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001660 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001661 });
1662 }
1663 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1664 displayDevice->undefinedRegion.set(bounds);
1665 displayDevice->undefinedRegion.subtractSelf(
1666 tr.transform(opaqueRegion));
1667 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001668 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001669 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001670}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001671
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001672// pickColorMode translates a given dataspace into the best available color mode.
1673// Currently only support sRGB and Display-P3.
1674android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1675 switch (dataSpace) {
1676 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1677 // system expects.
1678 case HAL_DATASPACE_UNKNOWN:
1679 case HAL_DATASPACE_SRGB:
1680 case HAL_DATASPACE_V0_SRGB:
1681 return HAL_COLOR_MODE_SRGB;
1682 break;
1683
1684 case HAL_DATASPACE_DISPLAY_P3:
1685 return HAL_COLOR_MODE_DISPLAY_P3;
1686 break;
1687
1688 default:
1689 // TODO (courtneygo): Do we want to assert an error here?
1690 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1691 dataSpace);
1692 return HAL_COLOR_MODE_SRGB;
1693 break;
1694 }
1695}
1696
1697android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1698 // Only support sRGB and Display-P3 right now.
1699 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1700 return HAL_DATASPACE_DISPLAY_P3;
1701 }
1702 return HAL_DATASPACE_V0_SRGB;
1703}
1704
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 ATRACE_CALL();
1707 ALOGV("setUpHWComposer");
1708
Jesse Hall028dc8f2013-08-20 16:35:32 -07001709 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001710 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1711 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1712 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1713
1714 // If nothing has changed (!dirty), don't recompose.
1715 // If something changed, but we don't currently have any visible layers,
1716 // and didn't when we last did a composition, then skip it this time.
1717 // The second rule does two things:
1718 // - When all layers are removed from a display, we'll emit one black
1719 // frame, then nothing more until we get new layers.
1720 // - When a display is created with a private layer stack, we won't
1721 // emit any black frames until a layer is added to the layer stack.
1722 bool mustRecompose = dirty && !(empty && wasEmpty);
1723
1724 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1725 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1726 mustRecompose ? "doing" : "skipping",
1727 dirty ? "+" : "-",
1728 empty ? "+" : "-",
1729 wasEmpty ? "+" : "-");
1730
Dan Stoza71433162014-02-04 16:22:36 -08001731 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001732
1733 if (mustRecompose) {
1734 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1735 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001736 }
1737
Dan Stoza9e56aa02015-11-02 13:00:03 -08001738 // build the h/w work list
1739 if (CC_UNLIKELY(mGeometryInvalid)) {
1740 mGeometryInvalid = false;
1741 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1742 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1743 const auto hwcId = displayDevice->getHwcDisplayId();
1744 if (hwcId >= 0) {
1745 const Vector<sp<Layer>>& currentLayers(
1746 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001747 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001748 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 if (!layer->hasHwcLayer(hwcId)) {
1750 auto hwcLayer = mHwc->createLayer(hwcId);
1751 if (hwcLayer) {
1752 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1753 } else {
1754 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001756 }
1757 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001758
Robert Carrae060832016-11-28 10:51:00 -08001759 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001760 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001762 }
1763 }
1764 }
1765 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766 }
Riley Andrews03414a12014-07-01 14:22:59 -07001767
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001768
1769 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1770
Dan Stoza9e56aa02015-11-02 13:00:03 -08001771 // Set the per-frame data
1772 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1773 auto& displayDevice = mDisplays[displayId];
1774 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001775
Dan Stoza9e56aa02015-11-02 13:00:03 -08001776 if (hwcId < 0) {
1777 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001778 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001779 if (colorMatrix != mPreviousColorMatrix) {
1780 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1781 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1782 "display %zd: %d", displayId, result);
1783 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1785 layer->setPerFrameData(displayDevice);
1786 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001787
1788 if (hasWideColorDisplay) {
1789 android_color_mode newColorMode;
1790 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1791
1792 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1793 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1794 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1795 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1796 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1797 }
1798 newColorMode = pickColorMode(newDataSpace);
1799
1800 setActiveColorModeInternal(displayDevice, newColorMode);
1801 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001802 }
1803
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001804 mPreviousColorMatrix = colorMatrix;
1805
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001807 auto& displayDevice = mDisplays[displayId];
1808 if (!displayDevice->isDisplayOn()) {
1809 continue;
1810 }
1811
1812 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1814 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001815 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001817
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818void SurfaceFlinger::doComposition() {
1819 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820 ALOGV("doComposition");
1821
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001822 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001823 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001824 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001825 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001826 // transform the dirty region into this screen's coordinate space
1827 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001828
1829 // repaint the framebuffer (if needed)
1830 doDisplayComposition(hw, dirtyRegion);
1831
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832 hw->dirtyRegion.clear();
1833 hw->flip(hw->swapRegion);
1834 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001835 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001837 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001838}
1839
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001840void SurfaceFlinger::postFramebuffer()
1841{
Mathias Agopian841cde52012-03-01 15:44:37 -08001842 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001844
Mathias Agopiana44b0412011-10-16 18:46:35 -07001845 const nsecs_t now = systemTime();
1846 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001847
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1849 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001850 if (!displayDevice->isDisplayOn()) {
1851 continue;
1852 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 const auto hwcId = displayDevice->getHwcDisplayId();
1854 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001855 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001856 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001857 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001858 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1860 sp<Fence> releaseFence = Fence::NO_FENCE;
1861 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1862 releaseFence = displayDevice->getClientTargetAcquireFence();
1863 } else {
1864 auto hwcLayer = layer->getHwcLayer(hwcId);
1865 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001866 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 layer->onLayerDisplayed(releaseFence);
1868 }
1869 if (hwcId >= 0) {
1870 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001871 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001872 }
1873
Mathias Agopiana44b0412011-10-16 18:46:35 -07001874 mLastSwapBufferTime = systemTime() - now;
1875 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001876
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001877 // |mStateLock| not needed as we are on the main thread
1878 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001879 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1880 logFrameStats();
1881 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001882}
1883
Mathias Agopian87baae12012-07-31 12:38:26 -07001884void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885{
Mathias Agopian841cde52012-03-01 15:44:37 -08001886 ATRACE_CALL();
1887
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001888 // here we keep a copy of the drawing state (that is the state that's
1889 // going to be overwritten by handleTransactionLocked()) outside of
1890 // mStateLock so that the side-effects of the State assignment
1891 // don't happen with mStateLock held (which can cause deadlocks).
1892 State drawingState(mDrawingState);
1893
Mathias Agopianca4d3602011-05-19 15:38:14 -07001894 Mutex::Autolock _l(mStateLock);
1895 const nsecs_t now = systemTime();
1896 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001897
Mathias Agopianca4d3602011-05-19 15:38:14 -07001898 // Here we're guaranteed that some transaction flags are set
1899 // so we can call handleTransactionLocked() unconditionally.
1900 // We call getTransactionFlags(), which will also clear the flags,
1901 // with mStateLock held to guarantee that mCurrentState won't change
1902 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001903
Mathias Agopiane57f2922012-08-09 16:29:12 -07001904 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001905 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001906
Mathias Agopianca4d3602011-05-19 15:38:14 -07001907 mLastTransactionTime = systemTime() - now;
1908 mDebugInTransaction = 0;
1909 invalidateHwcGeometry();
1910 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001911}
1912
Mathias Agopian87baae12012-07-31 12:38:26 -07001913void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001914{
Dan Stoza7dde5992015-05-22 09:51:44 -07001915 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001916 mCurrentState.traverseInZOrder([](Layer* layer) {
1917 layer->notifyAvailableFrames();
1918 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001920 /*
1921 * Traversal of the children
1922 * (perform the transaction for each of them if needed)
1923 */
1924
Mathias Agopian3559b072012-08-15 13:46:03 -07001925 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001926 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001927 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001928 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929
1930 const uint32_t flags = layer->doTransaction(0);
1931 if (flags & Layer::eVisibleRegion)
1932 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001933 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934 }
1935
1936 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001937 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938 */
1939
Mathias Agopiane57f2922012-08-09 16:29:12 -07001940 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001941 // here we take advantage of Vector's copy-on-write semantics to
1942 // improve performance by skipping the transaction entirely when
1943 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001944 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1945 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001946 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001948 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001949 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001950
1951 // find the displays that were removed
1952 // (ie: in drawing state but not in current state)
1953 // also handle displays that changed
1954 // (ie: displays that are in both lists)
1955 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001956 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1957 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001958 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001959 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001960 // Call makeCurrent() on the primary display so we can
1961 // be sure that nothing associated with this display
1962 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001963 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001964 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001965 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07001966 if (hw != NULL)
1967 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001968 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001969 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001970 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001971 } else {
1972 ALOGW("trying to remove the main display");
1973 }
1974 } else {
1975 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001976 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001977 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001978 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1979 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001980 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001981 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001982 // recreating the DisplayDevice, so we just remove it
1983 // from the drawing state, so that it get re-added
1984 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001985 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07001986 if (hw != NULL)
1987 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001988 mDisplays.removeItem(display);
1989 mDrawingState.displays.removeItemsAt(i);
1990 dc--; i--;
1991 // at this point we must loop to the next item
1992 continue;
1993 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001994
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001995 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001996 if (disp != NULL) {
1997 if (state.layerStack != draw[i].layerStack) {
1998 disp->setLayerStack(state.layerStack);
1999 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002000 if ((state.orientation != draw[i].orientation)
2001 || (state.viewport != draw[i].viewport)
2002 || (state.frame != draw[i].frame))
2003 {
2004 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002005 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002006 }
Michael Lentine47e45402014-07-18 15:34:25 -07002007 if (state.width != draw[i].width || state.height != draw[i].height) {
2008 disp->setDisplaySize(state.width, state.height);
2009 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002010 }
2011 }
2012 }
2013
2014 // find displays that were added
2015 // (ie: in current state but not in drawing state)
2016 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002017 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002018 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002019
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002020 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002021 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002022 sp<IGraphicBufferProducer> bqProducer;
2023 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002024 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002025
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002027 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002028 // Virtual displays without a surface are dormant:
2029 // they have external state (layer stack, projection,
2030 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002031 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002032
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002033 // Allow VR composer to use virtual displays.
2034 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002035 int width = 0;
2036 int status = state.surface->query(
2037 NATIVE_WINDOW_WIDTH, &width);
2038 ALOGE_IF(status != NO_ERROR,
2039 "Unable to query width (%d)", status);
2040 int height = 0;
2041 status = state.surface->query(
2042 NATIVE_WINDOW_HEIGHT, &height);
2043 ALOGE_IF(status != NO_ERROR,
2044 "Unable to query height (%d)", status);
2045 int intFormat = 0;
2046 status = state.surface->query(
2047 NATIVE_WINDOW_FORMAT, &intFormat);
2048 ALOGE_IF(status != NO_ERROR,
2049 "Unable to query format (%d)", status);
2050 auto format = static_cast<android_pixel_format_t>(
2051 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002052
Dan Stoza8cf150a2016-08-02 10:27:31 -07002053 mHwc->allocateVirtualDisplay(width, height, &format,
2054 &hwcId);
2055 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002056
Dan Stoza5cf424b2016-05-20 14:02:39 -07002057 // TODO: Plumb requested format back up to consumer
2058
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 sp<VirtualDisplaySurface> vds =
2060 new VirtualDisplaySurface(*mHwc,
2061 hwcId, state.surface, bqProducer,
2062 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002063
2064 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002065 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002066 }
2067 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002068 ALOGE_IF(state.surface!=NULL,
2069 "adding a supported display, but rendering "
2070 "surface is provided (%p), ignoring it",
2071 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002072
2073 hwcId = state.type;
2074 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2075 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002076 }
2077
2078 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002079 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002080 sp<DisplayDevice> hw =
2081 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2082 dispSurface, producer,
2083 mRenderEngine->getEGLConfig(),
2084 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002085 hw->setLayerStack(state.layerStack);
2086 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002087 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002088 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002089 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002090 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002091 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002092 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002093 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002094 }
2095 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002096 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002097 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098
Mathias Agopian84300952012-11-21 16:02:13 -08002099 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2100 // The transform hint might have changed for some layers
2101 // (either because a display has changed, or because a layer
2102 // as changed).
2103 //
2104 // Walk through all the layers in currentLayers,
2105 // and update their transform hint.
2106 //
2107 // If a layer is visible only on a single display, then that
2108 // display is used to calculate the hint, otherwise we use the
2109 // default display.
2110 //
2111 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2112 // the hint is set before we acquire a buffer from the surface texture.
2113 //
2114 // NOTE: layer transactions have taken place already, so we use their
2115 // drawing state. However, SurfaceFlinger's own transaction has not
2116 // happened yet, so we must use the current state layer list
2117 // (soon to become the drawing state list).
2118 //
2119 sp<const DisplayDevice> disp;
2120 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002121 bool first = true;
2122 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002123 // NOTE: we rely on the fact that layers are sorted by
2124 // layerStack first (so we don't have to traverse the list
2125 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002126 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002127 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002128 currentlayerStack = layerStack;
2129 // figure out if this layerstack is mirrored
2130 // (more than one display) if so, pick the default display,
2131 // if not, pick the only display it's on.
2132 disp.clear();
2133 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2134 sp<const DisplayDevice> hw(mDisplays[dpy]);
2135 if (hw->getLayerStack() == currentlayerStack) {
2136 if (disp == NULL) {
2137 disp = hw;
2138 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002139 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002140 break;
2141 }
2142 }
2143 }
2144 }
Chet Haase91d25932013-04-11 15:24:55 -07002145 if (disp == NULL) {
2146 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2147 // redraw after transform hint changes. See bug 8508397.
2148
2149 // could be null when this layer is using a layerStack
2150 // that is not visible on any display. Also can occur at
2151 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002152 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002153 }
Chet Haase91d25932013-04-11 15:24:55 -07002154 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002155
2156 first = false;
2157 });
Mathias Agopian84300952012-11-21 16:02:13 -08002158 }
2159
2160
Mathias Agopian3559b072012-08-15 13:46:03 -07002161 /*
2162 * Perform our own transaction if needed
2163 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002164
2165 if (mLayersAdded) {
2166 mLayersAdded = false;
2167 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002168 mVisibleRegionsDirty = true;
2169 }
2170
2171 // some layers might have been removed, so
2172 // we need to update the regions they're exposing.
2173 if (mLayersRemoved) {
2174 mLayersRemoved = false;
2175 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002176 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002178 // this layer is not visible anymore
2179 // TODO: we could traverse the tree from front to back and
2180 // compute the actual visible region
2181 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002182 Region visibleReg;
2183 visibleReg.set(layer->computeScreenBounds());
2184 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002185 }
Robert Carr2047fae2016-11-28 14:09:09 -08002186 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002187 }
2188
2189 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002190
2191 updateCursorAsync();
2192}
2193
2194void SurfaceFlinger::updateCursorAsync()
2195{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2197 auto& displayDevice = mDisplays[displayId];
2198 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002199 continue;
2200 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002201
2202 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2203 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002204 }
2205 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002206}
2207
2208void SurfaceFlinger::commitTransaction()
2209{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002210 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002211 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002212 for (const auto& l : mLayersPendingRemoval) {
2213 recordBufferingStats(l->getName().string(),
2214 l->getOccupancyHistory(true));
2215 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002216 }
2217 mLayersPendingRemoval.clear();
2218 }
2219
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002220 // If this transaction is part of a window animation then the next frame
2221 // we composite should be considered an animation as well.
2222 mAnimCompositionPending = mAnimTransactionPending;
2223
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002225 mDrawingState.traverseInZOrder([](Layer* layer) {
2226 layer->commitChildList();
2227 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002228 mTransactionPending = false;
2229 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002230 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002231}
2232
Robert Carr2047fae2016-11-28 14:09:09 -08002233void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002234 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235{
Mathias Agopian841cde52012-03-01 15:44:37 -08002236 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239 Region aboveOpaqueLayers;
2240 Region aboveCoveredLayers;
2241 Region dirty;
2242
Mathias Agopian87baae12012-07-31 12:38:26 -07002243 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244
Robert Carr2047fae2016-11-28 14:09:09 -08002245 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002247 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248
Jesse Hall01e29052013-02-19 16:13:35 -08002249 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002250 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002251 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002252
Mathias Agopianab028732010-03-16 16:41:46 -07002253 /*
2254 * opaqueRegion: area of a surface that is fully opaque.
2255 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002257
2258 /*
2259 * visibleRegion: area of a surface that is visible on screen
2260 * and not fully transparent. This is essentially the layer's
2261 * footprint minus the opaque regions above it.
2262 * Areas covered by a translucent surface are considered visible.
2263 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002264 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002265
2266 /*
2267 * coveredRegion: area of a surface that is covered by all
2268 * visible regions above it (which includes the translucent areas).
2269 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002270 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002271
Jesse Halla8026d22012-09-25 13:25:04 -07002272 /*
2273 * transparentRegion: area of a surface that is hinted to be completely
2274 * transparent. This is only used to tell when the layer has no visible
2275 * non-transparent regions and can be removed from the layer list. It
2276 * does not affect the visibleRegion of this layer or any layers
2277 * beneath it. The hint may not be correct if apps don't respect the
2278 * SurfaceView restrictions (which, sadly, some don't).
2279 */
2280 Region transparentRegion;
2281
Mathias Agopianab028732010-03-16 16:41:46 -07002282
2283 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002284 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002285 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002286 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002288 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002289 if (!visibleRegion.isEmpty()) {
2290 // Remove the transparent area from the visible region
2291 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002292 if (tr.preserveRects()) {
2293 // transform the transparent region
2294 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002296 // transformation too complex, can't do the
2297 // transparent region optimization.
2298 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002299 }
Mathias Agopianab028732010-03-16 16:41:46 -07002300 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301
Mathias Agopianab028732010-03-16 16:41:46 -07002302 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002303 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002305 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2306 // the opaque region is the layer's footprint
2307 opaqueRegion = visibleRegion;
2308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309 }
2310 }
2311
Mathias Agopianab028732010-03-16 16:41:46 -07002312 // Clip the covered region to the visible region
2313 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2314
2315 // Update aboveCoveredLayers for next (lower) layer
2316 aboveCoveredLayers.orSelf(visibleRegion);
2317
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318 // subtract the opaque region covered by the layers above us
2319 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320
2321 // compute this layer's dirty region
2322 if (layer->contentDirty) {
2323 // we need to invalidate the whole region
2324 dirty = visibleRegion;
2325 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002326 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 layer->contentDirty = false;
2328 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002329 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002330 * the exposed region consists of two components:
2331 * 1) what's VISIBLE now and was COVERED before
2332 * 2) what's EXPOSED now less what was EXPOSED before
2333 *
2334 * note that (1) is conservative, we start with the whole
2335 * visible region but only keep what used to be covered by
2336 * something -- which mean it may have been exposed.
2337 *
2338 * (2) handles areas that were not covered by anything but got
2339 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002340 */
Mathias Agopianab028732010-03-16 16:41:46 -07002341 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002342 const Region oldVisibleRegion = layer->visibleRegion;
2343 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002344 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2345 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 }
2347 dirty.subtractSelf(aboveOpaqueLayers);
2348
2349 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002350 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351
Mathias Agopianab028732010-03-16 16:41:46 -07002352 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002354
Jesse Halla8026d22012-09-25 13:25:04 -07002355 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 layer->setVisibleRegion(visibleRegion);
2357 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002358 layer->setVisibleNonTransparentRegion(
2359 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002360 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361
Mathias Agopian87baae12012-07-31 12:38:26 -07002362 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363}
2364
Mathias Agopian87baae12012-07-31 12:38:26 -07002365void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2366 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002367 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002368 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2369 if (hw->getLayerStack() == layerStack) {
2370 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002371 }
2372 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002373}
2374
Dan Stoza6b9454d2014-11-07 16:00:59 -08002375bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002377 ALOGV("handlePageFlip");
2378
Brian Andersond6927fb2016-07-23 23:37:30 -07002379 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380
Mathias Agopian4fec8732012-06-29 14:12:52 -07002381 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002382 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002383 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002384
2385 // Store the set of layers that need updates. This set must not change as
2386 // buffers are being latched, as this could result in a deadlock.
2387 // Example: Two producers share the same command stream and:
2388 // 1.) Layer 0 is latched
2389 // 2.) Layer 0 gets a new frame
2390 // 2.) Layer 1 gets a new frame
2391 // 3.) Layer 1 is latched.
2392 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2393 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002394 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002395 if (layer->hasQueuedFrame()) {
2396 frameQueued = true;
2397 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002398 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002399 } else {
2400 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002401 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002402 } else {
2403 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002404 }
Robert Carr2047fae2016-11-28 14:09:09 -08002405 });
2406
Dan Stoza9e56aa02015-11-02 13:00:03 -08002407 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002408 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002409 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002410 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002411 if (!dirty.isEmpty()) {
2412 newDataLatched = true;
2413 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002414 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002415
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002416 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002417
2418 // If we will need to wake up at some time in the future to deal with a
2419 // queued frame that shouldn't be displayed during this vsync period, wake
2420 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002422 signalLayerUpdate();
2423 }
2424
2425 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002426 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427}
2428
Mathias Agopianad456f92011-01-13 17:53:01 -08002429void SurfaceFlinger::invalidateHwcGeometry()
2430{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002431 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002432}
2433
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002434
Fabien Sanglard830b8472016-11-30 16:35:58 -08002435void SurfaceFlinger::doDisplayComposition(
2436 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002437 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438{
Dan Stoza71433162014-02-04 16:22:36 -08002439 // We only need to actually compose the display if:
2440 // 1) It is being handled by hardware composer, which may need this to
2441 // keep its virtual display state machine in sync, or
2442 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002443 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002444 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002445 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002446 return;
2447 }
2448
Dan Stoza9e56aa02015-11-02 13:00:03 -08002449 ALOGV("doDisplayComposition");
2450
Mathias Agopian87baae12012-07-31 12:38:26 -07002451 Region dirtyRegion(inDirtyRegion);
2452
Mathias Agopianb8a55602009-06-26 19:06:36 -07002453 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002454 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002455
Fabien Sanglard830b8472016-11-30 16:35:58 -08002456 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002457 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002458 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2459 // takes a rectangle, we must make sure to update that whole
2460 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002461 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002462 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002463 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002464 // We need to redraw the rectangle that will be updated
2465 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002466 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002467 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002468 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002469 } else {
2470 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002471 dirtyRegion.set(displayDevice->bounds());
2472 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 }
2474 }
2475
Fabien Sanglard830b8472016-11-30 16:35:58 -08002476 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002478 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002479 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002480
2481 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002482 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002483}
2484
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485bool SurfaceFlinger::doComposeSurfaces(
2486 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002487{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002489
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002491
2492 mat4 oldColorMatrix;
2493 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2494 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2495 if (applyColorMatrix) {
2496 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2497 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2498 }
2499
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2501 if (hasClientComposition) {
2502 ALOGV("hasClientComposition");
2503
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002504#ifdef USE_HWC2
2505 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2506 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2507#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002508 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002509 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002510 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002511 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002512
2513 // |mStateLock| not needed as we are on the main thread
2514 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002515 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2516 }
2517 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002518 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002519
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002520 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002521 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2522 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002523 // when using overlays, we assume a fully transparent framebuffer
2524 // NOTE: we could reduce how much we need to clear, for instance
2525 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002526 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002527 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002528 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002529 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002530 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002532
2533 // we remove the scissor part
2534 // we're left with the letterbox region
2535 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002537
2538 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002539 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002540
2541 // but limit it to the dirty region
2542 region.andSelf(dirty);
2543
Mathias Agopianb9494d52012-04-18 02:28:45 -07002544 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002545 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002546 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002547 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002548 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002549 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002550
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002552 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002553 // scissor on the main display. It should never be needed
2554 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555 const Rect& bounds(displayDevice->getBounds());
2556 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002557 if (scissor != bounds) {
2558 // scissor doesn't match the screen's dimensions, so we
2559 // need to clear everything outside of it and enable
2560 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002561
Mathias Agopianf45c5102012-10-24 16:29:17 -07002562 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002563 const uint32_t height = displayDevice->getHeight();
2564 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002565 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002566 }
2567 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002568 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002569
Mathias Agopian85d751c2012-08-29 16:59:24 -07002570 /*
2571 * and then, render the layers targeted at the framebuffer
2572 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002573
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 ALOGV("Rendering client layers");
2575 const Transform& displayTransform = displayDevice->getTransform();
2576 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002577 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 bool firstLayer = true;
2579 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2580 const Region clip(dirty.intersect(
2581 displayTransform.transform(layer->visibleRegion)));
2582 ALOGV("Layer: %s", layer->getName().string());
2583 ALOGV(" Composition type: %s",
2584 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002585 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 switch (layer->getCompositionType(hwcId)) {
2587 case HWC2::Composition::Cursor:
2588 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002589 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002590 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002591 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2593 layer->isOpaque(state) && (state.alpha == 1.0f)
2594 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002595 // never clear the very first layer since we're
2596 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002597 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002598 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002599 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002600 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 case HWC2::Composition::Client: {
2602 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002603 break;
2604 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002606 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002607 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 } else {
2609 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002610 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002612 }
2613 } else {
2614 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002615 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002616 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002618 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002620 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002621 }
2622 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002623
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002624 if (applyColorMatrix) {
2625 getRenderEngine().setupColorTransform(oldColorMatrix);
2626 }
2627
Mathias Agopianf45c5102012-10-24 16:29:17 -07002628 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002630 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631}
2632
Fabien Sanglard830b8472016-11-30 16:35:58 -08002633void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2634 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002635 RenderEngine& engine(getRenderEngine());
2636 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637}
2638
Dan Stoza7d89d062015-04-30 13:29:25 -07002639status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002640 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002641 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002642 const sp<Layer>& lbc,
2643 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002644{
Dan Stoza7d89d062015-04-30 13:29:25 -07002645 // add this layer to the current state list
2646 {
2647 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002648 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002649 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2650 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002651 return NO_MEMORY;
2652 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002653 if (parent == nullptr) {
2654 mCurrentState.layersSortedByZ.add(lbc);
2655 } else {
2656 parent->addChild(lbc);
2657 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002658 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002659 mLayersAdded = true;
2660 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002661 }
2662
Mathias Agopian96f08192010-06-02 23:28:45 -07002663 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002664 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002665
Dan Stoza7d89d062015-04-30 13:29:25 -07002666 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002667}
2668
Robert Carr9524cb32017-02-13 11:32:32 -08002669status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002670 Mutex::Autolock _l(mStateLock);
2671
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 const auto& p = layer->getParent();
2673 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2674 mCurrentState.layersSortedByZ.remove(layer);
2675
Robert Carr136e2f62017-02-08 17:54:29 -08002676 // As a matter of normal operation, the LayerCleaner will produce a second
2677 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2678 // so we will succeed in promoting it, but it's already been removed
2679 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2680 // otherwise something has gone wrong and we are leaking the layer.
2681 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2683 layer->getName().string(),
2684 (p != nullptr) ? p->getName().string() : "no-parent");
2685 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002686 } else if (index < 0) {
2687 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002688 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689
2690 mLayersPendingRemoval.add(layer);
2691 mLayersRemoved = true;
2692 mNumLayers--;
2693 setTransactionFlags(eTransactionNeeded);
2694 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695}
2696
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002697uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002698 return android_atomic_release_load(&mTransactionFlags);
2699}
2700
Mathias Agopian3f844832013-08-07 21:24:32 -07002701uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2703}
2704
Mathias Agopian3f844832013-08-07 21:24:32 -07002705uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002706 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2707 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002708 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709 }
2710 return old;
2711}
2712
Mathias Agopian8b33f032012-07-24 20:43:54 -07002713void SurfaceFlinger::setTransactionState(
2714 const Vector<ComposerState>& state,
2715 const Vector<DisplayState>& displays,
2716 uint32_t flags)
2717{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002718 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002719 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002720 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002721
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002722 if (flags & eAnimation) {
2723 // For window updates that are part of an animation we must wait for
2724 // previous animation "frames" to be handled.
2725 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002726 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002727 if (CC_UNLIKELY(err != NO_ERROR)) {
2728 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002729 // caller after a few seconds.
2730 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2731 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002732 mAnimTransactionPending = false;
2733 break;
2734 }
2735 }
2736 }
2737
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 size_t count = displays.size();
2739 for (size_t i=0 ; i<count ; i++) {
2740 const DisplayState& s(displays[i]);
2741 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002742 }
2743
Mathias Agopiane57f2922012-08-09 16:29:12 -07002744 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002745 for (size_t i=0 ; i<count ; i++) {
2746 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002747 // Here we need to check that the interface we're given is indeed
2748 // one of our own. A malicious client could give us a NULL
2749 // IInterface, or one of its own or even one of our own but a
2750 // different type. All these situations would cause us to crash.
2751 //
2752 // NOTE: it would be better to use RTTI as we could directly check
2753 // that we have a Client*. however, RTTI is disabled in Android.
2754 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002755 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002756 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002757 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002758 sp<Client> client( static_cast<Client *>(s.client.get()) );
2759 transactionFlags |= setClientStateLocked(client, s.state);
2760 }
2761 }
2762 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002763 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002764
Robert Carr2a7dbb42016-05-24 11:41:28 -07002765 // If a synchronous transaction is explicitly requested without any changes,
2766 // force a transaction anyway. This can be used as a flush mechanism for
2767 // previous async transactions.
2768 if (transactionFlags == 0 && (flags & eSynchronous)) {
2769 transactionFlags = eTransactionNeeded;
2770 }
2771
Mathias Agopian386aa982011-11-07 21:58:03 -08002772 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002773 if (mInterceptor.isEnabled()) {
2774 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2775 }
Irvel468051e2016-06-13 16:44:44 -07002776
Mathias Agopian386aa982011-11-07 21:58:03 -08002777 // this triggers the transaction
2778 setTransactionFlags(transactionFlags);
2779
2780 // if this is a synchronous transaction, wait for it to take effect
2781 // before returning.
2782 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002783 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002784 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002785 if (flags & eAnimation) {
2786 mAnimTransactionPending = true;
2787 }
2788 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002789 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2790 if (CC_UNLIKELY(err != NO_ERROR)) {
2791 // just in case something goes wrong in SF, return to the
2792 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002793 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2794 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002795 break;
2796 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002797 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002798 }
2799}
2800
Mathias Agopiane57f2922012-08-09 16:29:12 -07002801uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2802{
Jesse Hall9a143922012-10-04 16:29:19 -07002803 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2804 if (dpyIdx < 0)
2805 return 0;
2806
Mathias Agopiane57f2922012-08-09 16:29:12 -07002807 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002808 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002809 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002810 const uint32_t what = s.what;
2811 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002812 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813 disp.surface = s.surface;
2814 flags |= eDisplayTransactionNeeded;
2815 }
2816 }
2817 if (what & DisplayState::eLayerStackChanged) {
2818 if (disp.layerStack != s.layerStack) {
2819 disp.layerStack = s.layerStack;
2820 flags |= eDisplayTransactionNeeded;
2821 }
2822 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002823 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002824 if (disp.orientation != s.orientation) {
2825 disp.orientation = s.orientation;
2826 flags |= eDisplayTransactionNeeded;
2827 }
2828 if (disp.frame != s.frame) {
2829 disp.frame = s.frame;
2830 flags |= eDisplayTransactionNeeded;
2831 }
2832 if (disp.viewport != s.viewport) {
2833 disp.viewport = s.viewport;
2834 flags |= eDisplayTransactionNeeded;
2835 }
2836 }
Michael Lentine47e45402014-07-18 15:34:25 -07002837 if (what & DisplayState::eDisplaySizeChanged) {
2838 if (disp.width != s.width) {
2839 disp.width = s.width;
2840 flags |= eDisplayTransactionNeeded;
2841 }
2842 if (disp.height != s.height) {
2843 disp.height = s.height;
2844 flags |= eDisplayTransactionNeeded;
2845 }
2846 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002847 }
2848 return flags;
2849}
2850
2851uint32_t SurfaceFlinger::setClientStateLocked(
2852 const sp<Client>& client,
2853 const layer_state_t& s)
2854{
2855 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002856 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002857 if (layer != 0) {
2858 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002859 bool geometryAppliesWithResize =
2860 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002861 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002862 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002863 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002864 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002865 }
2866 if (what & layer_state_t::eLayerChanged) {
2867 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002868 const auto& p = layer->getParent();
2869 if (p == nullptr) {
2870 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2871 if (layer->setLayer(s.z) && idx >= 0) {
2872 mCurrentState.layersSortedByZ.removeAt(idx);
2873 mCurrentState.layersSortedByZ.add(layer);
2874 // we need traversal (state changed)
2875 // AND transaction (list changed)
2876 flags |= eTransactionNeeded|eTraversalNeeded;
2877 }
2878 } else {
2879 if (p->setChildLayer(layer, s.z)) {
2880 flags |= eTransactionNeeded|eTraversalNeeded;
2881 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002882 }
2883 }
Robert Carrdb66e622017-04-10 16:55:57 -07002884 if (what & layer_state_t::eRelativeLayerChanged) {
2885 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2886 flags |= eTransactionNeeded|eTraversalNeeded;
2887 }
2888 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 if (what & layer_state_t::eSizeChanged) {
2890 if (layer->setSize(s.w, s.h)) {
2891 flags |= eTraversalNeeded;
2892 }
2893 }
2894 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002895 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002896 flags |= eTraversalNeeded;
2897 }
2898 if (what & layer_state_t::eMatrixChanged) {
2899 if (layer->setMatrix(s.matrix))
2900 flags |= eTraversalNeeded;
2901 }
2902 if (what & layer_state_t::eTransparentRegionChanged) {
2903 if (layer->setTransparentRegionHint(s.transparentRegion))
2904 flags |= eTraversalNeeded;
2905 }
Dan Stoza23116082015-06-18 14:58:39 -07002906 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907 if (layer->setFlags(s.flags, s.mask))
2908 flags |= eTraversalNeeded;
2909 }
2910 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002911 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002912 flags |= eTraversalNeeded;
2913 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002914 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002915 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002916 flags |= eTraversalNeeded;
2917 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002918 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002919 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 // We only allow setting layer stacks for top level layers,
2921 // everything else inherits layer stack from its parent.
2922 if (layer->hasParent()) {
2923 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2924 layer->getName().string());
2925 } else if (idx < 0) {
2926 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2927 "that also does not appear in the top level layer list. Something"
2928 " has gone wrong.", layer->getName().string());
2929 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002930 mCurrentState.layersSortedByZ.removeAt(idx);
2931 mCurrentState.layersSortedByZ.add(layer);
2932 // we need traversal (state changed)
2933 // AND transaction (list changed)
2934 flags |= eTransactionNeeded|eTraversalNeeded;
2935 }
2936 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002937 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002938 if (s.barrierHandle != nullptr) {
2939 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2940 } else if (s.barrierGbp != nullptr) {
2941 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2942 if (authenticateSurfaceTextureLocked(gbp)) {
2943 const auto& otherLayer =
2944 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2945 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2946 } else {
2947 ALOGE("Attempt to defer transaction to to an"
2948 " unrecognized GraphicBufferProducer");
2949 }
2950 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002951 // We don't trigger a traversal here because if no other state is
2952 // changed, we don't want this to cause any more work
2953 }
Robert Carr1db73f62016-12-21 12:58:51 -08002954 if (what & layer_state_t::eReparentChildren) {
2955 if (layer->reparentChildren(s.reparentHandle)) {
2956 flags |= eTransactionNeeded|eTraversalNeeded;
2957 }
2958 }
Robert Carr9524cb32017-02-13 11:32:32 -08002959 if (what & layer_state_t::eDetachChildren) {
2960 layer->detachChildren();
2961 }
Robert Carrc3574f72016-03-24 12:19:32 -07002962 if (what & layer_state_t::eOverrideScalingModeChanged) {
2963 layer->setOverrideScalingMode(s.overrideScalingMode);
2964 // We don't trigger a traversal here because if no other state is
2965 // changed, we don't want this to cause any more work
2966 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002967 }
2968 return flags;
2969}
2970
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002971status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002972 const String8& name,
2973 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002974 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002975 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2976 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002978 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002979 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002980 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002981 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002982 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002983
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002984 status_t result = NO_ERROR;
2985
2986 sp<Layer> layer;
2987
Cody Northropbc755282017-03-31 12:00:08 -06002988 String8 uniqueName = getUniqueLayerName(name);
2989
Mathias Agopian3165cc22012-08-08 19:42:09 -07002990 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2991 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002992 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002993 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002994 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002996 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002997 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002998 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002999 handle, gbp, &layer);
3000 break;
3001 default:
3002 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003003 break;
3004 }
3005
Dan Stoza7d89d062015-04-30 13:29:25 -07003006 if (result != NO_ERROR) {
3007 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003009
Albert Chaulk479c60c2017-01-27 14:21:34 -05003010 layer->setInfo(windowType, ownerUid);
3011
Robert Carr1f0a16a2016-10-24 16:27:39 -07003012 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003013 if (result != NO_ERROR) {
3014 return result;
3015 }
Irvelffc9efc2016-07-27 15:16:37 -07003016 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003017
3018 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003019 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003020}
3021
Cody Northropbc755282017-03-31 12:00:08 -06003022String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3023{
3024 bool matchFound = true;
3025 uint32_t dupeCounter = 0;
3026
3027 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3028 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3029
3030 // Loop over layers until we're sure there is no matching name
3031 while (matchFound) {
3032 matchFound = false;
3033 mDrawingState.traverseInZOrder([&](Layer* layer) {
3034 if (layer->getName() == uniqueName) {
3035 matchFound = true;
3036 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3037 }
3038 });
3039 }
3040
3041 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3042
3043 return uniqueName;
3044}
3045
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003046status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3047 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3048 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049{
3050 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003051 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 case PIXEL_FORMAT_TRANSPARENT:
3053 case PIXEL_FORMAT_TRANSLUCENT:
3054 format = PIXEL_FORMAT_RGBA_8888;
3055 break;
3056 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003057 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058 break;
3059 }
3060
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003061 *outLayer = new Layer(this, client, name, w, h, flags);
3062 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3063 if (err == NO_ERROR) {
3064 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003065 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067
3068 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3069 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003072status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3073 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3074 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003076 *outLayer = new LayerDim(this, client, name, w, h, flags);
3077 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003078 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003079 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003080}
3081
Mathias Agopianac9fa422013-02-11 16:40:36 -08003082status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083{
Robert Carr9524cb32017-02-13 11:32:32 -08003084 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003085 status_t err = NO_ERROR;
3086 sp<Layer> l(client->getLayerUser(handle));
3087 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003088 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003089 err = removeLayer(l);
3090 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3091 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003092 }
3093 return err;
3094}
3095
Mathias Agopian13127d82013-03-05 17:47:11 -08003096status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003097{
Mathias Agopian67106042013-03-14 19:18:13 -07003098 // called by ~LayerCleaner() when all references to the IBinder (handle)
3099 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003100 sp<Layer> l = layer.promote();
3101 if (l == nullptr) {
3102 // The layer has already been removed, carry on
3103 return NO_ERROR;
3104 } if (l->getParent() != nullptr) {
3105 // If we have a parent, then we can continue to live as long as it does.
3106 return NO_ERROR;
3107 }
3108 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109}
3110
Mathias Agopianb60314a2012-04-10 22:09:54 -07003111// ---------------------------------------------------------------------------
3112
Andy McFadden13a082e2012-08-24 10:16:42 -07003113void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003114 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003115 Vector<ComposerState> state;
3116 Vector<DisplayState> displays;
3117 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003118 d.what = DisplayState::eDisplayProjectionChanged |
3119 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003120 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003121 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003122 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003123 d.frame.makeInvalid();
3124 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003125 d.width = 0;
3126 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003127 displays.add(d);
3128 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003129 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003130
Dan Stoza9e56aa02015-11-02 13:00:03 -08003131 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3132 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003133 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003134
Brian Andersond0010582017-03-07 13:20:31 -08003135 // Use phase of 0 since phase is not known.
3136 // Use latency of 0, which will snap to the ideal latency.
3137 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003138}
3139
3140void SurfaceFlinger::initializeDisplays() {
3141 class MessageScreenInitialized : public MessageBase {
3142 SurfaceFlinger* flinger;
3143 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003144 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003145 virtual bool handler() {
3146 flinger->onInitializeDisplays();
3147 return true;
3148 }
3149 };
3150 sp<MessageBase> msg = new MessageScreenInitialized(this);
3151 postMessageAsync(msg); // we may be called from main thread, use async message
3152}
3153
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003154void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3155 int mode) {
3156 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3157 this);
3158 int32_t type = hw->getDisplayType();
3159 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003160
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003161 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003162 return;
3163 }
3164
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003165 hw->setPowerMode(mode);
3166 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3167 ALOGW("Trying to set power mode for virtual display");
3168 return;
3169 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003170
Irvelffc9efc2016-07-27 15:16:37 -07003171 if (mInterceptor.isEnabled()) {
3172 Mutex::Autolock _l(mStateLock);
3173 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3174 if (idx < 0) {
3175 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3176 return;
3177 }
3178 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3179 }
3180
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003181 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003182 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003183 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003184 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3185 // FIXME: eventthread only knows about the main display right now
3186 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003187 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003188 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003190 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003191 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003192 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003193
3194 struct sched_param param = {0};
3195 param.sched_priority = 1;
3196 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3197 ALOGW("Couldn't set SCHED_FIFO on display on");
3198 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003199 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003200 // Turn off the display
3201 struct sched_param param = {0};
3202 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3203 ALOGW("Couldn't set SCHED_OTHER on display off");
3204 }
3205
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003206 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003207 disableHardwareVsync(true); // also cancels any in-progress resync
3208
Mathias Agopiancde87a32012-09-13 14:09:01 -07003209 // FIXME: eventthread only knows about the main display right now
3210 mEventThread->onScreenReleased();
3211 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003212
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213 getHwComposer().setPowerMode(type, mode);
3214 mVisibleRegionsDirty = true;
3215 // from this point on, SF will stop drawing on this display
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003216 } else if (mode == HWC_POWER_MODE_DOZE) {
3217 // Update display while dozing
3218 getHwComposer().setPowerMode(type, mode);
3219 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3220 // FIXME: eventthread only knows about the main display right now
3221 mEventThread->onScreenAcquired();
3222 resyncToHardwareVsync(true);
3223 }
3224 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3225 // Leave display going to doze
3226 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3227 disableHardwareVsync(true); // also cancels any in-progress resync
3228 // FIXME: eventthread only knows about the main display right now
3229 mEventThread->onScreenReleased();
3230 }
3231 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003232 } else {
3233 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003234 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003235}
3236
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003237void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3238 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003239 SurfaceFlinger& mFlinger;
3240 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003241 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003242 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003243 MessageSetPowerMode(SurfaceFlinger& flinger,
3244 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3245 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003246 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003247 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003248 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003249 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003250 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003251 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003252 ALOGW("Attempt to set power mode = %d for virtual display",
3253 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003254 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003255 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003256 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003257 return true;
3258 }
3259 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003260 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003261 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003262}
3263
3264// ---------------------------------------------------------------------------
3265
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3267{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003269
Mathias Agopianbd115332013-04-18 16:41:04 -07003270 IPCThreadState* ipc = IPCThreadState::self();
3271 const int pid = ipc->getCallingPid();
3272 const int uid = ipc->getCallingUid();
3273 if ((uid != AID_SHELL) &&
3274 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003275 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003276 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003278 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003279 // (this would indicate SF is stuck, but we want to be able to
3280 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003281 status_t err = mStateLock.timedLock(s2ns(1));
3282 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003283 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003284 result.appendFormat(
3285 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3286 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003287 }
3288
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003289 bool dumpAll = true;
3290 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003291 size_t numArgs = args.size();
3292 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003293 if ((index < numArgs) &&
3294 (args[index] == String16("--list"))) {
3295 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003296 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003297 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003298 }
3299
3300 if ((index < numArgs) &&
3301 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003302 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003303 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003304 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003305 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003306
3307 if ((index < numArgs) &&
3308 (args[index] == String16("--latency-clear"))) {
3309 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003310 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003311 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003312 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003313
3314 if ((index < numArgs) &&
3315 (args[index] == String16("--dispsync"))) {
3316 index++;
3317 mPrimaryDispSync.dump(result);
3318 dumpAll = false;
3319 }
Dan Stozab90cf072015-03-05 11:05:59 -08003320
3321 if ((index < numArgs) &&
3322 (args[index] == String16("--static-screen"))) {
3323 index++;
3324 dumpStaticScreenStats(result);
3325 dumpAll = false;
3326 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003327
3328 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003329 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003330 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003331 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003332 dumpAll = false;
3333 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003334
3335 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3336 index++;
3337 dumpWideColorInfo(result);
3338 dumpAll = false;
3339 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003341
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003342 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003343 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003344 }
3345
Mathias Agopian9795c422009-08-26 16:36:26 -07003346 if (locked) {
3347 mStateLock.unlock();
3348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003349 }
3350 write(fd, result.string(), result.size());
3351 return NO_ERROR;
3352}
3353
Dan Stozac7014012014-02-14 15:03:43 -08003354void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3355 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003356{
Robert Carr2047fae2016-11-28 14:09:09 -08003357 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003358 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003359 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003360}
3361
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003362void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003363 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003364{
3365 String8 name;
3366 if (index < args.size()) {
3367 name = String8(args[index]);
3368 index++;
3369 }
3370
Dan Stoza9e56aa02015-11-02 13:00:03 -08003371 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3372 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003373 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003374
3375 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003376 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003377 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003378 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003379 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003380 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003381 }
Robert Carr2047fae2016-11-28 14:09:09 -08003382 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003383 }
3384}
3385
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003386void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003387 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003388{
3389 String8 name;
3390 if (index < args.size()) {
3391 name = String8(args[index]);
3392 index++;
3393 }
3394
Robert Carr2047fae2016-11-28 14:09:09 -08003395 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003396 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003397 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003398 }
Robert Carr2047fae2016-11-28 14:09:09 -08003399 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003400
Svetoslavd85084b2014-03-20 10:28:31 -07003401 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003402}
3403
Jamie Gennis6547ff42013-07-16 20:12:42 -07003404// This should only be called from the main thread. Otherwise it would need
3405// the lock and should use mCurrentState rather than mDrawingState.
3406void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003407 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003408 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003409 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003410
3411 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3412}
3413
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003414void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003415{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003416 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003417 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3418
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003419 if (isLayerTripleBufferingDisabled())
3420 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003421
3422 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003423 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003424 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003425 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003426 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3427 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003428 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003429}
3430
Dan Stozab90cf072015-03-05 11:05:59 -08003431void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3432{
3433 result.appendFormat("Static screen stats:\n");
3434 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3435 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3436 float percent = 100.0f *
3437 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3438 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3439 b + 1, bucketTimeSec, percent);
3440 }
3441 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3442 float percent = 100.0f *
3443 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3444 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3445 NUM_BUCKETS - 1, bucketTimeSec, percent);
3446}
3447
Dan Stozae77c7662016-05-13 11:37:28 -07003448void SurfaceFlinger::recordBufferingStats(const char* layerName,
3449 std::vector<OccupancyTracker::Segment>&& history) {
3450 Mutex::Autolock lock(mBufferingStatsMutex);
3451 auto& stats = mBufferingStats[layerName];
3452 for (const auto& segment : history) {
3453 if (!segment.usedThirdBuffer) {
3454 stats.twoBufferTime += segment.totalTime;
3455 }
3456 if (segment.occupancyAverage < 1.0f) {
3457 stats.doubleBufferedTime += segment.totalTime;
3458 } else if (segment.occupancyAverage < 2.0f) {
3459 stats.tripleBufferedTime += segment.totalTime;
3460 }
3461 ++stats.numSegments;
3462 stats.totalTime += segment.totalTime;
3463 }
3464}
3465
Brian Andersond6927fb2016-07-23 23:37:30 -07003466void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3467 result.appendFormat("Layer frame timestamps:\n");
3468
3469 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3470 const size_t count = currentLayers.size();
3471 for (size_t i=0 ; i<count ; i++) {
3472 currentLayers[i]->dumpFrameEvents(result);
3473 }
3474}
3475
Dan Stozae77c7662016-05-13 11:37:28 -07003476void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3477 result.append("Buffering stats:\n");
3478 result.append(" [Layer name] <Active time> <Two buffer> "
3479 "<Double buffered> <Triple buffered>\n");
3480 Mutex::Autolock lock(mBufferingStatsMutex);
3481 typedef std::tuple<std::string, float, float, float> BufferTuple;
3482 std::map<float, BufferTuple, std::greater<float>> sorted;
3483 for (const auto& statsPair : mBufferingStats) {
3484 const char* name = statsPair.first.c_str();
3485 const BufferingStats& stats = statsPair.second;
3486 if (stats.numSegments == 0) {
3487 continue;
3488 }
3489 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3490 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3491 stats.totalTime;
3492 float doubleBufferRatio = static_cast<float>(
3493 stats.doubleBufferedTime) / stats.totalTime;
3494 float tripleBufferRatio = static_cast<float>(
3495 stats.tripleBufferedTime) / stats.totalTime;
3496 sorted.insert({activeTime, {name, twoBufferRatio,
3497 doubleBufferRatio, tripleBufferRatio}});
3498 }
3499 for (const auto& sortedPair : sorted) {
3500 float activeTime = sortedPair.first;
3501 const BufferTuple& values = sortedPair.second;
3502 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3503 std::get<0>(values).c_str(), activeTime,
3504 std::get<1>(values), std::get<2>(values),
3505 std::get<3>(values));
3506 }
3507 result.append("\n");
3508}
3509
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003510void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3511 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3512
3513 // TODO: print out if wide-color mode is active or not
3514
3515 for (size_t d = 0; d < mDisplays.size(); d++) {
3516 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3517 int32_t hwcId = displayDevice->getHwcDisplayId();
3518 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3519 continue;
3520 }
3521
3522 result.appendFormat("Display %d color modes:\n", hwcId);
3523 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3524 for (auto&& mode : modes) {
3525 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3526 }
3527
3528 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3529 result.appendFormat(" Current color mode: %s (%d)\n",
3530 decodeColorMode(currentMode).c_str(), currentMode);
3531 }
3532 result.append("\n");
3533}
3534
Mathias Agopian74d211a2013-04-22 16:55:35 +02003535void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3536 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003537{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003538 bool colorize = false;
3539 if (index < args.size()
3540 && (args[index] == String16("--color"))) {
3541 colorize = true;
3542 index++;
3543 }
3544
3545 Colorizer colorizer(colorize);
3546
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003547 // figure out if we're stuck somewhere
3548 const nsecs_t now = systemTime();
3549 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3550 const nsecs_t inTransaction(mDebugInTransaction);
3551 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3552 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3553
3554 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003555 * Dump library configuration.
3556 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003557
3558 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003559 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003560 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003561 appendSfConfigString(result);
3562 appendUiConfigString(result);
3563 appendGuiConfigString(result);
3564 result.append("\n");
3565
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003566 result.append("\nWide-Color information:\n");
3567 dumpWideColorInfo(result);
3568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003569 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003570 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003571 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003572 result.append(SyncFeatures::getInstance().toString());
3573 result.append("\n");
3574
Dan Stoza9e56aa02015-11-02 13:00:03 -08003575 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3576
Andy McFadden41d67d72014-04-25 16:58:34 -07003577 colorizer.bold(result);
3578 result.append("DispSync configuration: ");
3579 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003580 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003581 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003582 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003583 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003584 result.append("\n");
3585
Dan Stozab90cf072015-03-05 11:05:59 -08003586 // Dump static screen stats
3587 result.append("\n");
3588 dumpStaticScreenStats(result);
3589 result.append("\n");
3590
Dan Stozae77c7662016-05-13 11:37:28 -07003591 dumpBufferingStats(result);
3592
Andy McFadden4803b742012-09-24 19:07:20 -07003593 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003594 * Dump the visible layer list
3595 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003596 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003597 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003598 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003599 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003600 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003601 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003602
3603 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003604 * Dump Display state
3605 */
3606
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003607 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003608 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003609 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003610 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3611 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003612 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003613 }
3614
3615 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003616 * Dump SurfaceFlinger global state
3617 */
3618
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003619 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003620 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003621 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003622
Mathias Agopian888c8222012-08-04 21:10:38 -07003623 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003624 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003625
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003626 colorizer.bold(result);
3627 result.appendFormat("EGL implementation : %s\n",
3628 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3629 colorizer.reset(result);
3630 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003631 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003632
Mathias Agopian875d8e12013-06-07 15:35:48 -07003633 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003634
Mathias Agopian42977342012-08-05 00:40:46 -07003635 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003636 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3637 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003638 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003639 " last eglSwapBuffers() time: %f us\n"
3640 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003641 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003642 " refresh-rate : %f fps\n"
3643 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003644 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003645 " gpu_to_cpu_unsupported : %d\n"
3646 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003647 mLastSwapBufferTime/1000.0,
3648 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003649 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003650 1e9 / activeConfig->getVsyncPeriod(),
3651 activeConfig->getDpiX(),
3652 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003653 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003654
Mathias Agopian74d211a2013-04-22 16:55:35 +02003655 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003656 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003657
Mathias Agopian74d211a2013-04-22 16:55:35 +02003658 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003659 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003660
3661 /*
3662 * VSYNC state
3663 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003664 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003665 result.append("\n");
3666
3667 /*
3668 * HWC layer minidump
3669 */
3670 for (size_t d = 0; d < mDisplays.size(); d++) {
3671 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3672 int32_t hwcId = displayDevice->getHwcDisplayId();
3673 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3674 continue;
3675 }
3676
3677 result.appendFormat("Display %d HWC layers:\n", hwcId);
3678 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003679 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003680 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003681 });
Dan Stozae22aec72016-08-01 13:20:59 -07003682 result.append("\n");
3683 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003684
3685 /*
3686 * Dump HWComposer state
3687 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003688 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003689 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003690 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003691 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003692 result.appendFormat(" h/w composer %s\n",
3693 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003694 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003695
3696 /*
3697 * Dump gralloc state
3698 */
3699 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3700 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003701}
3702
Mathias Agopian13127d82013-03-05 17:47:11 -08003703const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003704SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003705 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003706 wp<IBinder> dpy;
3707 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3708 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3709 dpy = mDisplays.keyAt(i);
3710 break;
3711 }
3712 }
3713 if (dpy == NULL) {
3714 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3715 // Just use the primary display so we have something to return
3716 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3717 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003718 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003719}
3720
Keun young Park63f165f2012-08-31 10:53:36 -07003721bool SurfaceFlinger::startDdmConnection()
3722{
3723 void* libddmconnection_dso =
3724 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3725 if (!libddmconnection_dso) {
3726 return false;
3727 }
3728 void (*DdmConnection_start)(const char* name);
3729 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003730 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003731 if (!DdmConnection_start) {
3732 dlclose(libddmconnection_dso);
3733 return false;
3734 }
3735 (*DdmConnection_start)(getServiceName());
3736 return true;
3737}
3738
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003739status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740 switch (code) {
3741 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003742 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003744 case CLEAR_ANIMATION_FRAME_STATS:
3745 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003746 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003747 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 {
3749 // codes that require permission check
3750 IPCThreadState* ipc = IPCThreadState::self();
3751 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003752 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003753 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003754 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003755 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003756 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003757 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003758 break;
3759 }
Robert Carr1db73f62016-12-21 12:58:51 -08003760 /*
3761 * Calling setTransactionState is safe, because you need to have been
3762 * granted a reference to Client* and Handle* to do anything with it.
3763 *
3764 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3765 */
3766 case SET_TRANSACTION_STATE:
3767 case CREATE_SCOPED_CONNECTION:
3768 {
3769 return OK;
3770 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003771 case CAPTURE_SCREEN:
3772 {
3773 // codes that require permission check
3774 IPCThreadState* ipc = IPCThreadState::self();
3775 const int pid = ipc->getCallingPid();
3776 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003777 if ((uid != AID_GRAPHICS) &&
3778 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003779 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003780 return PERMISSION_DENIED;
3781 }
3782 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 }
3784 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003785 return OK;
3786}
3787
3788status_t SurfaceFlinger::onTransact(
3789 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3790{
3791 status_t credentialCheck = CheckTransactCodeCredentials(code);
3792 if (credentialCheck != OK) {
3793 return credentialCheck;
3794 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003795
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3797 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003798 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003799 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003800 IPCThreadState* ipc = IPCThreadState::self();
3801 const int pid = ipc->getCallingPid();
3802 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003803 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003804 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003805 return PERMISSION_DENIED;
3806 }
3807 int n;
3808 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003809 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003810 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 return NO_ERROR;
3812 case 1002: // SHOW_UPDATES
3813 n = data.readInt32();
3814 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003815 invalidateHwcGeometry();
3816 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003819 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003820 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003822 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003823 setTransactionFlags(
3824 eTransactionNeeded|
3825 eDisplayTransactionNeeded|
3826 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003827 return NO_ERROR;
3828 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003829 case 1006:{ // send empty update
3830 signalRefresh();
3831 return NO_ERROR;
3832 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003833 case 1008: // toggle use of hw composer
3834 n = data.readInt32();
3835 mDebugDisableHWC = n ? 1 : 0;
3836 invalidateHwcGeometry();
3837 repaintEverything();
3838 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003839 case 1009: // toggle use of transform hint
3840 n = data.readInt32();
3841 mDebugDisableTransformHint = n ? 1 : 0;
3842 invalidateHwcGeometry();
3843 repaintEverything();
3844 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003846 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847 reply->writeInt32(0);
3848 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003849 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003850 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003851 return NO_ERROR;
3852 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003853 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003854 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003855 return NO_ERROR;
3856 }
3857 case 1014: {
3858 // daltonize
3859 n = data.readInt32();
3860 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003861 case 1:
3862 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3863 break;
3864 case 2:
3865 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3866 break;
3867 case 3:
3868 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3869 break;
3870 default:
3871 mDaltonizer.setType(ColorBlindnessType::None);
3872 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003873 }
3874 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003875 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003876 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003877 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003878 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003879 invalidateHwcGeometry();
3880 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003881 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003883 case 1015: {
3884 // apply a color matrix
3885 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003886 if (n) {
3887 // color matrix is sent as mat3 matrix followed by vec3
3888 // offset, then packed into a mat4 where the last row is
3889 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003890 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003891 for (size_t j = 0; j < 4; j++) {
3892 mColorMatrix[i][j] = data.readFloat();
3893 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003894 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003895 } else {
3896 mColorMatrix = mat4();
3897 }
3898 invalidateHwcGeometry();
3899 repaintEverything();
3900 return NO_ERROR;
3901 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003902 // This is an experimental interface
3903 // Needs to be shifted to proper binder interface when we productize
3904 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003905 n = data.readInt32();
3906 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003907 return NO_ERROR;
3908 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003909 case 1017: {
3910 n = data.readInt32();
3911 mForceFullDamage = static_cast<bool>(n);
3912 return NO_ERROR;
3913 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003914 case 1018: { // Modify Choreographer's phase offset
3915 n = data.readInt32();
3916 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3917 return NO_ERROR;
3918 }
3919 case 1019: { // Modify SurfaceFlinger's phase offset
3920 n = data.readInt32();
3921 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3922 return NO_ERROR;
3923 }
Irvel468051e2016-06-13 16:44:44 -07003924 case 1020: { // Layer updates interceptor
3925 n = data.readInt32();
3926 if (n) {
3927 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003928 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003929 }
3930 else{
3931 ALOGV("Interceptor disabled");
3932 mInterceptor.disable();
3933 }
3934 return NO_ERROR;
3935 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003936 case 1021: { // Disable HWC virtual displays
3937 n = data.readInt32();
3938 mUseHwcVirtualDisplays = !n;
3939 return NO_ERROR;
3940 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941 }
3942 }
3943 return err;
3944}
3945
Mathias Agopian53331da2011-08-22 21:44:41 -07003946void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003947 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003948 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003949}
3950
Mathias Agopian59119e62010-10-11 12:37:43 -07003951// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003952// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003953// ---------------------------------------------------------------------------
3954
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003955/* The code below is here to handle b/8734824
3956 *
3957 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003958 * from the surfaceflinger thread to the calling binder thread, where they
3959 * are executed. This allows the calling thread in the calling process to be
3960 * reused and not depend on having "enough" binder threads to handle the
3961 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003962 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003963class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003964 /* Parts of GraphicProducerWrapper are run on two different threads,
3965 * communicating by sending messages via Looper but also by shared member
3966 * data. Coherence maintenance is subtle and in places implicit (ugh).
3967 *
3968 * Don't rely on Looper's sendMessage/handleMessage providing
3969 * release/acquire semantics for any data not actually in the Message.
3970 * Data going from surfaceflinger to binder threads needs to be
3971 * synchronized explicitly.
3972 *
3973 * Barrier open/wait do provide release/acquire semantics. This provides
3974 * implicit synchronization for data coming back from binder to
3975 * surfaceflinger threads.
3976 */
3977
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003978 sp<IGraphicBufferProducer> impl;
3979 sp<Looper> looper;
3980 status_t result;
3981 bool exitPending;
3982 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003983 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003984 uint32_t code;
3985 Parcel const* data;
3986 Parcel* reply;
3987
3988 enum {
3989 MSG_API_CALL,
3990 MSG_EXIT
3991 };
3992
3993 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003994 * Called on surfaceflinger thread. This is called by our "fake"
3995 * BpGraphicBufferProducer. We package the data and reply Parcel and
3996 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003997 */
3998 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003999 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004000 this->code = code;
4001 this->data = &data;
4002 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004003 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004004 // if we've exited, we run the message synchronously right here.
4005 // note (JH): as far as I can tell from looking at the code, this
4006 // never actually happens. if it does, i'm not sure if it happens
4007 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004008 handleMessage(Message(MSG_API_CALL));
4009 } else {
4010 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004011 // Prevent stores to this->{code, data, reply} from being
4012 // reordered later than the construction of Message.
4013 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004014 looper->sendMessage(this, Message(MSG_API_CALL));
4015 barrier.wait();
4016 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004017 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004018 }
4019
4020 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004021 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004022 * call the real BpGraphicBufferProducer.
4023 */
4024 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004025 int what = message.what;
4026 // Prevent reads below from happening before the read from Message
4027 atomic_thread_fence(memory_order_acquire);
4028 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004029 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004030 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004031 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004032 exitRequested = true;
4033 }
4034 }
4035
4036public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004037 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004038 : impl(impl),
4039 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004040 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004041 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004042 exitRequested(false),
4043 code(0),
4044 data(NULL),
4045 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004046 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004047
Jesse Hallb154c422014-07-13 12:47:02 -07004048 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004049 status_t waitForResponse() {
4050 do {
4051 looper->pollOnce(-1);
4052 } while (!exitRequested);
4053 return result;
4054 }
4055
Jesse Hallb154c422014-07-13 12:47:02 -07004056 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004057 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004058 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004059 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004060 // Ensure this->result is visible to the binder thread before it
4061 // handles the message.
4062 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004063 looper->sendMessage(this, Message(MSG_EXIT));
4064 }
4065};
4066
4067
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004068status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4069 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004070 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004071 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004072 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004073
4074 if (CC_UNLIKELY(display == 0))
4075 return BAD_VALUE;
4076
4077 if (CC_UNLIKELY(producer == 0))
4078 return BAD_VALUE;
4079
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004080 // if we have secure windows on this display, never allow the screen capture
4081 // unless the producer interface is local (i.e.: we can take a screenshot for
4082 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004083 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004084
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004085 // Convert to surfaceflinger's internal rotation type.
4086 Transform::orientation_flags rotationFlags;
4087 switch (rotation) {
4088 case ISurfaceComposer::eRotateNone:
4089 rotationFlags = Transform::ROT_0;
4090 break;
4091 case ISurfaceComposer::eRotate90:
4092 rotationFlags = Transform::ROT_90;
4093 break;
4094 case ISurfaceComposer::eRotate180:
4095 rotationFlags = Transform::ROT_180;
4096 break;
4097 case ISurfaceComposer::eRotate270:
4098 rotationFlags = Transform::ROT_270;
4099 break;
4100 default:
4101 rotationFlags = Transform::ROT_0;
4102 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4103 break;
4104 }
4105
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004106 class MessageCaptureScreen : public MessageBase {
4107 SurfaceFlinger* flinger;
4108 sp<IBinder> display;
4109 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004110 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004111 uint32_t reqWidth, reqHeight;
4112 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004113 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004114 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004115 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004116 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004117 public:
4118 MessageCaptureScreen(SurfaceFlinger* flinger,
4119 const sp<IBinder>& display,
4120 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004121 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004122 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004123 bool useIdentityTransform,
4124 Transform::orientation_flags rotation,
4125 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004126 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004127 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004128 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004129 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004130 rotation(rotation), result(PERMISSION_DENIED),
4131 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004132 {
4133 }
4134 status_t getResult() const {
4135 return result;
4136 }
4137 virtual bool handler() {
4138 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004139 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004140 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004141 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004142 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004143 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004144 return true;
4145 }
4146 };
4147
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004148 // this creates a "fake" BBinder which will serve as a "fake" remote
4149 // binder to receive the marshaled calls and forward them to the
4150 // real remote (a BpGraphicBufferProducer)
4151 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4152
4153 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4154 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004155 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004156 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004157 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004158 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004159
4160 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004161 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004162 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004163 }
4164 return res;
4165}
4166
Mathias Agopian180f10d2013-04-10 22:55:41 -07004167
4168void SurfaceFlinger::renderScreenImplLocked(
4169 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004170 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004171 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004172 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004173{
4174 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004175 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004176
4177 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004178 const int32_t hw_w = hw->getWidth();
4179 const int32_t hw_h = hw->getHeight();
4180 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004181 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004182
Dan Stozac1879002014-05-22 15:59:05 -07004183 // if a default or invalid sourceCrop is passed in, set reasonable values
4184 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4185 !sourceCrop.isValid()) {
4186 sourceCrop.setLeftTop(Point(0, 0));
4187 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4188 }
4189
4190 // ensure that sourceCrop is inside screen
4191 if (sourceCrop.left < 0) {
4192 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4193 }
Dan Stozabe31f442014-06-11 11:20:54 -07004194 if (sourceCrop.right > hw_w) {
4195 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004196 }
4197 if (sourceCrop.top < 0) {
4198 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4199 }
Dan Stozabe31f442014-06-11 11:20:54 -07004200 if (sourceCrop.bottom > hw_h) {
4201 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004202 }
4203
Mathias Agopian180f10d2013-04-10 22:55:41 -07004204 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004205 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004206
4207 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004208 engine.setViewportAndProjection(
4209 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004210 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004211
4212 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004213 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004214
Robert Carr1f0a16a2016-10-24 16:27:39 -07004215 // We loop through the first level of layers without traversing,
4216 // as we need to interpret min/max layer Z in the top level Z space.
4217 for (const auto& layer : mDrawingState.layersSortedByZ) {
4218 if (layer->getLayerStack() != hw->getLayerStack()) {
4219 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004220 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004221 const Layer::State& state(layer->getDrawingState());
4222 if (state.z < minLayerZ || state.z > maxLayerZ) {
4223 continue;
4224 }
Dan Stoza412903f2017-04-27 13:42:17 -07004225 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004226 if (!layer->isVisible()) {
4227 return;
4228 }
4229 if (filtering) layer->setFiltering(true);
4230 layer->draw(hw, useIdentityTransform);
4231 if (filtering) layer->setFiltering(false);
4232 });
4233 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004234
Mathias Agopian931bda12013-08-28 18:11:46 -07004235 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004236}
4237
4238
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004239status_t SurfaceFlinger::captureScreenImplLocked(
4240 const sp<const DisplayDevice>& hw,
4241 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004242 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004243 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004244 bool useIdentityTransform, Transform::orientation_flags rotation,
4245 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004246{
4247 ATRACE_CALL();
4248
Mathias Agopian180f10d2013-04-10 22:55:41 -07004249 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004250 uint32_t hw_w = hw->getWidth();
4251 uint32_t hw_h = hw->getHeight();
4252
4253 if (rotation & Transform::ROT_90) {
4254 std::swap(hw_w, hw_h);
4255 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004256
Mathias Agopian180f10d2013-04-10 22:55:41 -07004257 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4258 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4259 reqWidth, reqHeight, hw_w, hw_h);
4260 return BAD_VALUE;
4261 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004262
Mathias Agopian180f10d2013-04-10 22:55:41 -07004263 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4264 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4265
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004266 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004267 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004268 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004269 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4270 (state.z < minLayerZ || state.z > maxLayerZ)) {
4271 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004272 }
Dan Stoza412903f2017-04-27 13:42:17 -07004273 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004274 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4275 layer->isSecure());
4276 });
4277 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004278
4279 if (!isLocalScreenshot && secureLayerIsVisible) {
4280 ALOGW("FB is protected: PERMISSION_DENIED");
4281 return PERMISSION_DENIED;
4282 }
4283
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004284 // create a surface (because we're a producer, and we need to
4285 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004286 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004287
4288 // Put the screenshot Surface into async mode so that
4289 // Layer::headFenceHasSignaled will always return true and we'll latch the
4290 // first buffer regardless of whether or not its acquire fence has
4291 // signaled. This is needed to avoid a race condition in the rotation
4292 // animation. See b/30209608
4293 sur->setAsyncMode(true);
4294
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004295 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004296
Michael Lentine5a16a622015-05-21 13:48:24 -07004297 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4298 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004299 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4300 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004301
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004302 int err = 0;
4303 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004304 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004305 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4306 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004307
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004308 if (err == NO_ERROR) {
4309 ANativeWindowBuffer* buffer;
4310 /* TODO: Once we have the sync framework everywhere this can use
4311 * server-side waits on the fence that dequeueBuffer returns.
4312 */
4313 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4314 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004315 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004316 // create an EGLImage from the buffer so we can later
4317 // turn it into a texture
4318 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4319 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4320 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004321 // this binds the given EGLImage as a framebuffer for the
4322 // duration of this scope.
4323 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4324 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004325 // this will in fact render into our dequeued buffer
4326 // via an FBO, which means we didn't have to create
4327 // an EGLSurface and therefore we're not
4328 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004329 renderScreenImplLocked(
4330 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4331 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004332
Riley Andrews86639902014-08-15 12:27:24 -07004333 // Attempt to create a sync khr object that can produce a sync point. If that
4334 // isn't available, create a non-dupable sync object in the fallback path and
4335 // wait on it directly.
4336 EGLSyncKHR sync;
4337 if (!DEBUG_SCREENSHOTS) {
4338 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004339 // native fence fd will not be populated until flush() is done.
4340 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004341 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004342 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004343 }
Riley Andrews86639902014-08-15 12:27:24 -07004344 if (sync != EGL_NO_SYNC_KHR) {
4345 // get the sync fd
4346 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4347 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4348 ALOGW("captureScreen: failed to dup sync khr object");
4349 syncFd = -1;
4350 }
4351 eglDestroySyncKHR(mEGLDisplay, sync);
4352 } else {
4353 // fallback path
4354 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4355 if (sync != EGL_NO_SYNC_KHR) {
4356 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4357 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4358 EGLint eglErr = eglGetError();
4359 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4360 ALOGW("captureScreen: fence wait timed out");
4361 } else {
4362 ALOGW_IF(eglErr != EGL_SUCCESS,
4363 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4364 }
4365 eglDestroySyncKHR(mEGLDisplay, sync);
4366 } else {
4367 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4368 }
4369 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004370 if (DEBUG_SCREENSHOTS) {
4371 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4372 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4373 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4374 hw, minLayerZ, maxLayerZ);
4375 delete [] pixels;
4376 }
4377
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004378 } else {
4379 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4380 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004381 window->cancelBuffer(window, buffer, syncFd);
4382 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004383 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004384 // destroy our image
4385 eglDestroyImageKHR(mEGLDisplay, image);
4386 } else {
4387 result = BAD_VALUE;
4388 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004389 if (buffer) {
4390 // queueBuffer takes ownership of syncFd
4391 result = window->queueBuffer(window, buffer, syncFd);
4392 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004393 }
4394 } else {
4395 result = BAD_VALUE;
4396 }
4397 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4398 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004399
Mathias Agopian74c40c02010-09-29 13:02:36 -07004400 return result;
4401}
4402
Mathias Agopiand5556842013-09-19 17:08:37 -07004403void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004404 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004405 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004406 for (size_t y=0 ; y<h ; y++) {
4407 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4408 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004409 if (p[x] != 0xFF000000) return;
4410 }
4411 }
4412 ALOGE("*** we just took a black screenshot ***\n"
4413 "requested minz=%d, maxz=%d, layerStack=%d",
4414 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004415
Robert Carr2047fae2016-11-28 14:09:09 -08004416 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004417 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004418 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004419 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4420 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004421 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004422 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4423 layer->isVisible() ? '+' : '-',
4424 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004425 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004426 i++;
4427 });
4428 }
4429 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004430 }
4431}
4432
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004433// ---------------------------------------------------------------------------
4434
Dan Stoza412903f2017-04-27 13:42:17 -07004435void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4436 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004437}
4438
Dan Stoza412903f2017-04-27 13:42:17 -07004439void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4440 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004441}
4442
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004443}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004444
4445
4446#if defined(__gl_h_)
4447#error "don't include gl/gl.h in this file"
4448#endif
4449
4450#if defined(__gl2_h_)
4451#error "don't include gl2/gl2.h in this file"
4452#endif