blob: 26baaaecb2408510ccdbd48caae2d9342752550c [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>
Romain Guyf8b4ca52017-03-16 18:39:20 +000048#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800121bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800122int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600123bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700126 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700128 mTransactionPending(false),
129 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700131 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700132 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800133 mHwc(nullptr),
134 mRealHwc(nullptr),
135 mVrHwc(nullptr),
136 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800152 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000153 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700154 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700155 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700160 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 mNumLayers(0),
162 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
Steven Thomas050b2c82017-03-06 11:45:16 -0800187 // Vr flinger is only enabled on Daydream ready devices.
188 useVrFlinger = getBool< ISurfaceFlingerConfigs,
189 &ISurfaceFlingerConfigs::useVrFlinger>(false);
190
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
192 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
193
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600194 hasWideColorDisplay =
195 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 // debugging stuff...
198 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700201 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showupdates", value, "0");
204 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 property_get("debug.sf.ddms", value, "0");
207 mDebugDDMS = atoi(value);
208 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700209 if (!startDdmConnection()) {
210 // start failed, and DDMS debugging not enabled
211 mDebugDDMS = 0;
212 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700213 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700214 ALOGI_IF(mDebugRegion, "showupdates enabled");
215 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700216
217 property_get("debug.sf.disable_backpressure", value, "0");
218 mPropagateBackpressure = !atoi(value);
219 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700220
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800221 property_get("debug.sf.enable_hwc_vds", value, "0");
222 mUseHwcVirtualDisplays = atoi(value);
223 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800225 property_get("ro.sf.disable_triple_buffer", value, "1");
226 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230void SurfaceFlinger::onFirstRef()
231{
232 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235SurfaceFlinger::~SurfaceFlinger()
236{
Mathias Agopiana4912602012-07-12 14:25:33 -0700237 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
238 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
239 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
Romain Guyf8b4ca52017-03-16 18:39:20 +0000343sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
344{
345 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
346 return gba;
347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
574 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800575 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800576 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
578
Jesse Hall692c7232012-11-08 15:41:56 -0800579 Mutex::Autolock _l(mStateLock);
580
Steven Thomas050b2c82017-03-06 11:45:16 -0800581 if (useVrFlinger) {
582 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
583 mVrFlingerRequestsDisplay = requestDisplay;
584 signalTransaction();
585 };
586 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
587 vrFlingerRequestDisplayCallback);
588 if (!mVrFlinger) {
589 ALOGE("Failed to start vrflinger");
590 }
591 }
592
Mathias Agopian875d8e12013-06-07 15:35:48 -0700593 // retrieve the EGL context that was selected/created
594 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700595
Mathias Agopianda27af92012-09-13 18:17:13 -0700596 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
597 "couldn't create EGLContext");
598
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 // make the GLContext current so that we can create textures when creating
600 // Layers (which may happens before we render something)
Polina Bondarenko80c02322017-04-10 10:15:42 +0000601 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700602
Jamie Gennisd1700752013-10-14 12:22:52 -0700603 mEventControlThread = new EventControlThread(this);
604 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
605
Mathias Agopian92a979a2012-08-02 18:32:23 -0700606 // initialize our drawing state
607 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700608
Andy McFadden13a082e2012-08-24 10:16:42 -0700609 // set initial conditions (e.g. unblank default device)
610 initializeDisplays();
611
Dan Stoza4e637772016-07-28 13:31:51 -0700612 mRenderEngine->primeCache();
613
Wei Wangb254fa32017-01-31 17:43:23 -0800614 mStartBootAnimThread = new StartBootAnimThread();
615 if (mStartBootAnimThread->Start() != NO_ERROR) {
616 ALOGE("Run StartBootAnimThread failed!");
617 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800618
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700620}
621
Mathias Agopiana67e4182012-06-19 17:26:12 -0700622void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800623 // Start boot animation service by setting a property mailbox
624 // if property setting thread is already running, Start() will be just a NOP
625 mStartBootAnimThread->Start();
626 // Wait until property was set
627 if (mStartBootAnimThread->join() != NO_ERROR) {
628 ALOGE("Join StartBootAnimThread failed!");
629 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700630}
631
Mathias Agopian875d8e12013-06-07 15:35:48 -0700632size_t SurfaceFlinger::getMaxTextureSize() const {
633 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700634}
635
Mathias Agopian875d8e12013-06-07 15:35:48 -0700636size_t SurfaceFlinger::getMaxViewportDims() const {
637 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700638}
639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800641
Jamie Gennis582270d2011-08-17 18:19:00 -0700642bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800643 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800644 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800645 return authenticateSurfaceTextureLocked(bufferProducer);
646}
647
648bool SurfaceFlinger::authenticateSurfaceTextureLocked(
649 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800650 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700651 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800652}
653
Dan Stoza7f7da322014-05-02 15:26:25 -0700654status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
655 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700656 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700657 return BAD_VALUE;
658 }
659
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500660 if (!display.get())
661 return NAME_NOT_FOUND;
662
Jesse Hall692c7232012-11-08 15:41:56 -0800663 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700664 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800665 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700666 type = i;
667 break;
668 }
669 }
670
671 if (type < 0) {
672 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700673 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700674
Mathias Agopian8b736f12012-08-13 17:54:26 -0700675 // TODO: Not sure if display density should handled by SF any longer
676 class Density {
677 static int getDensityFromProperty(char const* propName) {
678 char property[PROPERTY_VALUE_MAX];
679 int density = 0;
680 if (property_get(propName, property, NULL) > 0) {
681 density = atoi(property);
682 }
683 return density;
684 }
685 public:
686 static int getEmuDensity() {
687 return getDensityFromProperty("qemu.sf.lcd_density"); }
688 static int getBuildDensity() {
689 return getDensityFromProperty("ro.sf.lcd_density"); }
690 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700691
Dan Stoza7f7da322014-05-02 15:26:25 -0700692 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700693
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700695 DisplayInfo info = DisplayInfo();
696
Dan Stoza9e56aa02015-11-02 13:00:03 -0800697 float xdpi = hwConfig->getDpiX();
698 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700699
700 if (type == DisplayDevice::DISPLAY_PRIMARY) {
701 // The density of the device is provided by a build property
702 float density = Density::getBuildDensity() / 160.0f;
703 if (density == 0) {
704 // the build doesn't provide a density -- this is wrong!
705 // use xdpi instead
706 ALOGE("ro.sf.lcd_density must be defined as a build property");
707 density = xdpi / 160.0f;
708 }
709 if (Density::getEmuDensity()) {
710 // if "qemu.sf.lcd_density" is specified, it overrides everything
711 xdpi = ydpi = density = Density::getEmuDensity();
712 density /= 160.0f;
713 }
714 info.density = density;
715
716 // TODO: this needs to go away (currently needed only by webkit)
Polina Bondarenko80c02322017-04-10 10:15:42 +0000717 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
718 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 } else {
720 // TODO: where should this value come from?
721 static const int TV_DENSITY = 213;
722 info.density = TV_DENSITY / 160.0f;
723 info.orientation = 0;
724 }
725
Dan Stoza9e56aa02015-11-02 13:00:03 -0800726 info.w = hwConfig->getWidth();
727 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700728 info.xdpi = xdpi;
729 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900731 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732
Andy McFadden91b2ca82014-06-13 14:04:23 -0700733 // This is how far in advance a buffer must be queued for
734 // presentation at a given time. If you want a buffer to appear
735 // on the screen at time N, you must submit the buffer before
736 // (N - presentationDeadline).
737 //
738 // Normally it's one full refresh period (to give SF a chance to
739 // latch the buffer), but this can be reduced by configuring a
740 // DispSync offset. Any additional delays introduced by the hardware
741 // composer or panel must be accounted for here.
742 //
743 // We add an additional 1ms to allow for processing time and
744 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800745 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800746 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700747
748 // All non-virtual displays are currently considered secure.
749 info.secure = true;
750
Michael Wright28f24d02016-07-12 13:30:53 -0700751 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 }
753
Dan Stoza7f7da322014-05-02 15:26:25 -0700754 return NO_ERROR;
755}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700756
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800757status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700758 DisplayStatInfo* stats) {
759 if (stats == NULL) {
760 return BAD_VALUE;
761 }
762
763 // FIXME for now we always return stats for the primary display
764 memset(stats, 0, sizeof(*stats));
765 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
766 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
767 return NO_ERROR;
768}
769
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700770int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800771 if (display == NULL) {
772 ALOGE("%s : display is NULL", __func__);
773 return BAD_VALUE;
774 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700775 sp<DisplayDevice> device(getDisplayDevice(display));
776 if (device != NULL) {
777 return device->getActiveConfig();
778 }
779 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700780}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700781
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700782void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
783 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
784 this);
785 int32_t type = hw->getDisplayType();
786 int currentMode = hw->getActiveConfig();
787
788 if (mode == currentMode) {
789 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
790 return;
791 }
792
793 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
794 ALOGW("Trying to set config for virtual display");
795 return;
796 }
797
798 hw->setActiveConfig(mode);
799 getHwComposer().setActiveConfig(type, mode);
800}
801
802status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
803 class MessageSetActiveConfig: public MessageBase {
804 SurfaceFlinger& mFlinger;
805 sp<IBinder> mDisplay;
806 int mMode;
807 public:
808 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
809 int mode) :
810 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
811 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700812 Vector<DisplayInfo> configs;
813 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700814 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700815 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700816 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700817 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700818 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700819 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
820 if (hw == NULL) {
821 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700822 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700823 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
824 ALOGW("Attempt to set active config = %d for virtual display",
825 mMode);
826 } else {
827 mFlinger.setActiveConfigInternal(hw, mMode);
828 }
829 return true;
830 }
831 };
832 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
833 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700834 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835}
Michael Wright28f24d02016-07-12 13:30:53 -0700836status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
837 Vector<android_color_mode_t>* outColorModes) {
838 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
839 return BAD_VALUE;
840 }
841
842 if (!display.get()) {
843 return NAME_NOT_FOUND;
844 }
845
846 int32_t type = NAME_NOT_FOUND;
847 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
848 if (display == mBuiltinDisplays[i]) {
849 type = i;
850 break;
851 }
852 }
853
854 if (type < 0) {
855 return type;
856 }
857
858 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
859 outColorModes->clear();
860 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
861
862 return NO_ERROR;
863}
864
865android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
866 sp<DisplayDevice> device(getDisplayDevice(display));
867 if (device != nullptr) {
868 return device->getActiveColorMode();
869 }
870 return static_cast<android_color_mode_t>(BAD_VALUE);
871}
872
873void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
874 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700875 int32_t type = hw->getDisplayType();
876 android_color_mode_t currentMode = hw->getActiveColorMode();
877
878 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700879 return;
880 }
881
882 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
883 ALOGW("Trying to set config for virtual display");
884 return;
885 }
886
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600887 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
888 hw->getDisplayType());
889
Michael Wright28f24d02016-07-12 13:30:53 -0700890 hw->setActiveColorMode(mode);
891 getHwComposer().setActiveColorMode(type, mode);
892}
893
894
895status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
896 android_color_mode_t colorMode) {
897 class MessageSetActiveColorMode: public MessageBase {
898 SurfaceFlinger& mFlinger;
899 sp<IBinder> mDisplay;
900 android_color_mode_t mMode;
901 public:
902 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
903 android_color_mode_t mode) :
904 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
905 virtual bool handler() {
906 Vector<android_color_mode_t> modes;
907 mFlinger.getDisplayColorModes(mDisplay, &modes);
908 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
909 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600910 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
911 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700912 return true;
913 }
914 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
915 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600916 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
917 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700918 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600919 ALOGW("Attempt to set active color mode %s %d for virtual display",
920 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700921 } else {
922 mFlinger.setActiveColorModeInternal(hw, mMode);
923 }
924 return true;
925 }
926 };
927 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
928 postMessageSync(msg);
929 return NO_ERROR;
930}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700931
Svetoslavd85084b2014-03-20 10:28:31 -0700932status_t SurfaceFlinger::clearAnimationFrameStats() {
933 Mutex::Autolock _l(mStateLock);
934 mAnimFrameTracker.clearStats();
935 return NO_ERROR;
936}
937
938status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
939 Mutex::Autolock _l(mStateLock);
940 mAnimFrameTracker.getStats(outStats);
941 return NO_ERROR;
942}
943
Dan Stozac4f471e2016-03-24 09:31:08 -0700944status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
945 HdrCapabilities* outCapabilities) const {
946 Mutex::Autolock _l(mStateLock);
947
948 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
949 if (displayDevice == nullptr) {
950 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
951 return BAD_VALUE;
952 }
953
954 std::unique_ptr<HdrCapabilities> capabilities =
955 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
956 if (capabilities) {
957 std::swap(*outCapabilities, *capabilities);
958 } else {
959 return BAD_VALUE;
960 }
961
962 return NO_ERROR;
963}
964
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700965status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
966 if (enable == mInjectVSyncs) {
967 return NO_ERROR;
968 }
969
970 if (enable) {
971 mInjectVSyncs = enable;
972 ALOGV("VSync Injections enabled");
973 if (mVSyncInjector.get() == nullptr) {
974 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700975 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700976 }
977 mEventQueue.setEventThread(mInjectorEventThread);
978 } else {
979 mInjectVSyncs = enable;
980 ALOGV("VSync Injections disabled");
981 mEventQueue.setEventThread(mSFEventThread);
982 mVSyncInjector.clear();
983 }
984 return NO_ERROR;
985}
986
987status_t SurfaceFlinger::injectVSync(nsecs_t when) {
988 if (!mInjectVSyncs) {
989 ALOGE("VSync Injections not enabled");
990 return BAD_VALUE;
991 }
992 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
993 ALOGV("Injecting VSync inside SurfaceFlinger");
994 mVSyncInjector->onInjectSyncEvent(when);
995 }
996 return NO_ERROR;
997}
998
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800999// ----------------------------------------------------------------------------
1000
1001sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001002 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001003}
1004
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001005// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001006
1007void SurfaceFlinger::waitForEvent() {
1008 mEventQueue.waitMessage();
1009}
1010
1011void SurfaceFlinger::signalTransaction() {
1012 mEventQueue.invalidate();
1013}
1014
1015void SurfaceFlinger::signalLayerUpdate() {
1016 mEventQueue.invalidate();
1017}
1018
1019void SurfaceFlinger::signalRefresh() {
1020 mEventQueue.refresh();
1021}
1022
1023status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001024 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001025 return mEventQueue.postMessage(msg, reltime);
1026}
1027
1028status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001029 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001030 status_t res = mEventQueue.postMessage(msg, reltime);
1031 if (res == NO_ERROR) {
1032 msg->wait();
1033 }
1034 return res;
1035}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001036
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001037void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001038 do {
1039 waitForEvent();
1040 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041}
1042
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001043void SurfaceFlinger::enableHardwareVsync() {
1044 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001045 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001046 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001047 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1048 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001049 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001050 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001051}
1052
Jesse Hall948fe0c2013-10-14 12:56:09 -07001053void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001054 Mutex::Autolock _l(mHWVsyncLock);
1055
Jesse Hall948fe0c2013-10-14 12:56:09 -07001056 if (makeAvailable) {
1057 mHWVsyncAvailable = true;
1058 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001059 // Hardware vsync is not currently available, so abort the resync
1060 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001061 return;
1062 }
1063
Dan Stoza9e56aa02015-11-02 13:00:03 -08001064 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1065 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001066
1067 mPrimaryDispSync.reset();
1068 mPrimaryDispSync.setPeriod(period);
1069
1070 if (!mPrimaryHWVsyncEnabled) {
1071 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001072 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1073 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 mPrimaryHWVsyncEnabled = true;
1075 }
1076}
1077
Jesse Hall948fe0c2013-10-14 12:56:09 -07001078void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079 Mutex::Autolock _l(mHWVsyncLock);
1080 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001081 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1082 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 mPrimaryDispSync.endResync();
1084 mPrimaryHWVsyncEnabled = false;
1085 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001086 if (makeUnavailable) {
1087 mHWVsyncAvailable = false;
1088 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089}
1090
Tim Murray4a4e4a22016-04-19 16:29:23 +00001091void SurfaceFlinger::resyncWithRateLimit() {
1092 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1093 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001094 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001095 }
1096}
1097
Steven Thomas3cfac282017-02-06 12:29:30 -08001098void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1099 nsecs_t timestamp) {
1100 Mutex::Autolock lock(mStateLock);
1101 // Ignore any vsyncs from the non-active hardware composer.
1102 if (composer != mHwc) {
1103 return;
1104 }
1105
Jamie Gennisd1700752013-10-14 12:22:52 -07001106 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107
Jamie Gennisd1700752013-10-14 12:22:52 -07001108 { // Scope for the lock
1109 Mutex::Autolock _l(mHWVsyncLock);
1110 if (type == 0 && mPrimaryHWVsyncEnabled) {
1111 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001112 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001113 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001114
1115 if (needsHwVsync) {
1116 enableHardwareVsync();
1117 } else {
1118 disableHardwareVsync(false);
1119 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001120}
1121
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001122void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001123 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001124 *compositorTiming = mCompositorTiming;
1125}
1126
Polina Bondarenko80c02322017-04-10 10:15:42 +00001127void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1129 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1130 Mutex::Autolock lock(mStateLock);
Polina Bondarenko80c02322017-04-10 10:15:42 +00001131
1132 // All non-virtual displays are currently considered secure.
1133 bool isSecure = true;
1134
1135 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1136
1137 // When we're using the vr composer, the assumption is that we've
1138 // already created the IBinder object for the primary display.
1139 if (!mHwc->isUsingVrComposer()) {
1140 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1141 }
1142
1143 wp<IBinder> token = mBuiltinDisplays[type];
1144
1145 sp<IGraphicBufferProducer> producer;
1146 sp<IGraphicBufferConsumer> consumer;
1147 BufferQueue::createBufferQueue(&producer, &consumer,
1148 new GraphicBufferAlloc());
1149
1150 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1151 DisplayDevice::DISPLAY_PRIMARY, consumer);
1152
1153 bool hasWideColorModes = false;
1154 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1155 for (android_color_mode_t colorMode : modes) {
1156 switch (colorMode) {
1157 case HAL_COLOR_MODE_DISPLAY_P3:
1158 case HAL_COLOR_MODE_ADOBE_RGB:
1159 case HAL_COLOR_MODE_DCI_P3:
1160 hasWideColorModes = true;
1161 break;
1162 default:
1163 break;
1164 }
1165 }
1166 sp<DisplayDevice> hw =
1167 new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1168 producer, mRenderEngine->getEGLConfig(),
1169 hasWideColorModes && hasWideColorDisplay);
1170 mDisplays.add(token, hw);
1171 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1172 if (hasWideColorModes && hasWideColorDisplay) {
1173 defaultColorMode = HAL_COLOR_MODE_SRGB;
1174 }
1175 setActiveColorModeInternal(hw, defaultColorMode);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001176 } else {
1177 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001178 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001179 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001180 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001181 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001182 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1183 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001184 }
1185 setTransactionFlags(eDisplayTransactionNeeded);
1186
Andy McFadden9e9689c2012-10-10 18:17:51 -07001187 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001188 }
Mathias Agopian86303202012-07-24 22:46:10 -07001189}
1190
Steven Thomas3cfac282017-02-06 12:29:30 -08001191void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1192 Mutex::Autolock lock(mStateLock);
1193 if (composer == mHwc) {
1194 repaintEverything();
1195 } else {
1196 // This isn't from our current hardware composer. If it's a callback
1197 // from the real composer, forward the refresh request to vr
1198 // flinger. Otherwise ignore it.
1199 if (!composer->isUsingVrComposer()) {
1200 mVrFlinger->OnHardwareComposerRefresh();
1201 }
1202 }
1203}
1204
Dan Stoza9e56aa02015-11-02 13:00:03 -08001205void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001206 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 getHwComposer().setVsyncEnabled(disp,
1208 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001209}
1210
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001211void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1212 for (size_t i = 0; i < layers.size(); ++i) {
1213 layers[i]->clearHwcLayers();
1214 }
1215}
1216
1217void SurfaceFlinger::resetHwc() {
1218 disableHardwareVsync(true);
1219 clearHwcLayers(mDrawingState.layersSortedByZ);
1220 clearHwcLayers(mCurrentState.layersSortedByZ);
1221 // Clear the drawing state so that the logic inside of
1222 // handleTransactionLocked will fire. It will determine the delta between
1223 // mCurrentState and mDrawingState and re-apply all changes when we make the
1224 // transition.
1225 mDrawingState.displays.clear();
1226 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001227 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001228}
1229
Steven Thomas050b2c82017-03-06 11:45:16 -08001230void SurfaceFlinger::updateVrFlinger() {
1231 if (!mVrFlinger)
1232 return;
1233 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1234 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001235 return;
1236 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001237 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001238 // Construct new HWComposer without holding any locks.
1239 mVrHwc = new HWComposer(true);
1240 ALOGV("Vr HWC created");
1241 }
Polina Bondarenko80c02322017-04-10 10:15:42 +00001242 {
1243 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001244
Polina Bondarenko80c02322017-04-10 10:15:42 +00001245 if (vrFlingerRequestsDisplay) {
1246 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001247
Polina Bondarenko80c02322017-04-10 10:15:42 +00001248 mHwc = mVrHwc;
1249 mVrFlinger->GrantDisplayOwnership();
1250 } else {
1251 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001252
Polina Bondarenko80c02322017-04-10 10:15:42 +00001253 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001254
Polina Bondarenko80c02322017-04-10 10:15:42 +00001255 mHwc = mRealHwc;
1256 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001257 }
1258
Polina Bondarenko80c02322017-04-10 10:15:42 +00001259 mVisibleRegionsDirty = true;
1260 invalidateHwcGeometry();
1261 android_atomic_or(1, &mRepaintEverything);
1262 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001263 }
Polina Bondarenko80c02322017-04-10 10:15:42 +00001264 if (mVrHwc) {
1265 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1266 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001267}
1268
Mathias Agopian4fec8732012-06-29 14:12:52 -07001269void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001270 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001272 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001273 bool frameMissed = !mHadClientComposition &&
1274 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001275 (mPreviousPresentFence->getSignalTime() ==
1276 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001277 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001278 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001279 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001280 signalLayerUpdate();
1281 break;
1282 }
1283
Steven Thomas050b2c82017-03-06 11:45:16 -08001284 // Now that we're going to make it to the handleMessageTransaction()
1285 // call below it's safe to call updateVrFlinger(), which will
1286 // potentially trigger a display handoff.
1287 updateVrFlinger();
1288
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 bool refreshNeeded = handleMessageTransaction();
1290 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001291 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001292 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001293 // Signal a refresh if a transaction modified the window state,
1294 // a new buffer was latched, or if HWC has requested a full
1295 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001296 signalRefresh();
1297 }
1298 break;
1299 }
1300 case MessageQueue::REFRESH: {
1301 handleMessageRefresh();
1302 break;
1303 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001304 }
1305}
1306
Dan Stoza6b9454d2014-11-07 16:00:59 -08001307bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001308 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001309 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001310 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001311 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001312 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001313 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001314}
1315
Dan Stoza6b9454d2014-11-07 16:00:59 -08001316bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001317 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001318 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001319}
1320
1321void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001322 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001323
Pablo Ceballos40845df2016-01-25 17:41:15 -08001324 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001325
Brian Andersond6927fb2016-07-23 23:37:30 -07001326 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001327 rebuildLayerStacks();
1328 setUpHWComposer();
1329 doDebugFlashRegions();
1330 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001331 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001332
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001333 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001334
1335 mHadClientComposition = false;
1336 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1337 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1338 mHadClientComposition = mHadClientComposition ||
1339 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1340 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001341
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001343}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001344
Mathias Agopiancd60f992012-08-16 16:28:27 -07001345void SurfaceFlinger::doDebugFlashRegions()
1346{
1347 // is debugging enabled
1348 if (CC_LIKELY(!mDebugRegion))
1349 return;
1350
1351 const bool repaintEverything = mRepaintEverything;
1352 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1353 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001354 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001355 // transform the dirty region into this screen's coordinate space
1356 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1357 if (!dirtyRegion.isEmpty()) {
1358 // redraw the whole screen
1359 doComposeSurfaces(hw, Region(hw->bounds()));
1360
1361 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001363 RenderEngine& engine(getRenderEngine());
1364 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1365
Mathias Agopianda27af92012-09-13 18:17:13 -07001366 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001367 }
1368 }
1369 }
1370
1371 postFramebuffer();
1372
1373 if (mDebugRegion > 1) {
1374 usleep(mDebugRegion * 1000);
1375 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001376
Dan Stoza9e56aa02015-11-02 13:00:03 -08001377 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001378 auto& displayDevice = mDisplays[displayId];
1379 if (!displayDevice->isDisplayOn()) {
1380 continue;
1381 }
1382
1383 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1385 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001386 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387}
1388
Brian Andersond6927fb2016-07-23 23:37:30 -07001389void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001390{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001391 ATRACE_CALL();
1392 ALOGV("preComposition");
1393
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001395 mDrawingState.traverseInZOrder([&](Layer* layer) {
1396 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001397 needExtraInvalidate = true;
1398 }
Robert Carr2047fae2016-11-28 14:09:09 -08001399 });
1400
Mathias Agopiancd60f992012-08-16 16:28:27 -07001401 if (needExtraInvalidate) {
1402 signalLayerUpdate();
1403 }
1404}
1405
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001406void SurfaceFlinger::updateCompositorTiming(
1407 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1408 std::shared_ptr<FenceTime>& presentFenceTime) {
1409 // Update queue of past composite+present times and determine the
1410 // most recently known composite to present latency.
1411 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1412 nsecs_t compositeToPresentLatency = -1;
1413 while (!mCompositePresentTimes.empty()) {
1414 CompositePresentTime& cpt = mCompositePresentTimes.front();
1415 // Cached values should have been updated before calling this method,
1416 // which helps avoid duplicate syscalls.
1417 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1418 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1419 break;
1420 }
1421 compositeToPresentLatency = displayTime - cpt.composite;
1422 mCompositePresentTimes.pop();
1423 }
1424
1425 // Don't let mCompositePresentTimes grow unbounded, just in case.
1426 while (mCompositePresentTimes.size() > 16) {
1427 mCompositePresentTimes.pop();
1428 }
1429
Brian Andersond0010582017-03-07 13:20:31 -08001430 setCompositorTimingSnapped(
1431 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1432}
1433
1434void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1435 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001436 // Integer division and modulo round toward 0 not -inf, so we need to
1437 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001438 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001439 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1440 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1441
Brian Andersond0010582017-03-07 13:20:31 -08001442 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1443 if (idealLatency <= 0) {
1444 idealLatency = vsyncInterval;
1445 }
1446
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001447 // Snap the latency to a value that removes scheduling jitter from the
1448 // composition and present times, which often have >1ms of jitter.
1449 // Reducing jitter is important if an app attempts to extrapolate
1450 // something (such as user input) to an accurate diasplay time.
1451 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1452 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001453 nsecs_t bias = vsyncInterval / 2;
1454 int64_t extraVsyncs =
1455 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1456 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1457 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001458
Brian Andersond0010582017-03-07 13:20:31 -08001459 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001460 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1461 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001462 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001463}
1464
1465void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 ATRACE_CALL();
1468 ALOGV("postComposition");
1469
Brian Anderson3546a3f2016-07-14 11:51:14 -07001470 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001471 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001472 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001473 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001474 }
1475
Polina Bondarenko80c02322017-04-10 10:15:42 +00001476 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001477
1478 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1479 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1480 glCompositionDoneFenceTime =
1481 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1482 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1483 } else {
1484 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1485 }
1486 mGlCompositionDoneTimeline.updateSignalTimes();
1487
Brian Anderson4e606e32017-03-16 15:34:57 -07001488 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1489 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1490 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001491 mDisplayTimeline.updateSignalTimes();
1492
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001493 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1494 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1495
1496 // We use the refreshStartTime which might be sampled a little later than
1497 // when we started doing work for this frame, but that should be okay
1498 // since updateCompositorTiming has snapping logic.
1499 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001500 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001501 CompositorTiming compositorTiming;
1502 {
1503 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1504 compositorTiming = mCompositorTiming;
1505 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506
Robert Carr2047fae2016-11-28 14:09:09 -08001507 mDrawingState.traverseInZOrder([&](Layer* layer) {
1508 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001509 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001510 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001511 recordBufferingStats(layer->getName().string(),
1512 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001513 }
Robert Carr2047fae2016-11-28 14:09:09 -08001514 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001515
Brian Anderson4e606e32017-03-16 15:34:57 -07001516 if (presentFence->isValid()) {
1517 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001518 enableHardwareVsync();
1519 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001520 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001521 }
1522 }
1523
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001524 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001525 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001526 enableHardwareVsync();
1527 }
1528 }
1529
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001530 if (mAnimCompositionPending) {
1531 mAnimCompositionPending = false;
1532
Brian Anderson4e606e32017-03-16 15:34:57 -07001533 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001534 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001535 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001536 } else {
1537 // The HWC doesn't support present fences, so use the refresh
1538 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001539 nsecs_t presentTime =
1540 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001541 mAnimFrameTracker.setActualPresentTime(presentTime);
1542 }
1543 mAnimFrameTracker.advanceFrame();
1544 }
Dan Stozab90cf072015-03-05 11:05:59 -08001545
1546 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1547 return;
1548 }
1549
1550 nsecs_t currentTime = systemTime();
1551 if (mHasPoweredOff) {
1552 mHasPoweredOff = false;
1553 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001554 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001555 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001556 if (numPeriods < NUM_BUCKETS - 1) {
1557 mFrameBuckets[numPeriods] += elapsedTime;
1558 } else {
1559 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1560 }
1561 mTotalTime += elapsedTime;
1562 }
1563 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001564}
1565
1566void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001567 ATRACE_CALL();
1568 ALOGV("rebuildLayerStacks");
1569
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001571 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1572 ATRACE_CALL();
1573 mVisibleRegionsDirty = false;
1574 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001575
Jeff Sharkey76488112017-02-27 14:15:18 -07001576 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1577 Region opaqueRegion;
1578 Region dirtyRegion;
1579 Vector<sp<Layer>> layersSortedByZ;
1580 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1581 const Transform& tr(displayDevice->getTransform());
1582 const Rect bounds(displayDevice->getBounds());
1583 if (displayDevice->isDisplayOn()) {
1584 computeVisibleRegions(
1585 displayDevice->getLayerStack(), dirtyRegion,
1586 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001587
Jeff Sharkey76488112017-02-27 14:15:18 -07001588 mDrawingState.traverseInZOrder([&](Layer* layer) {
1589 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1590 Region drawRegion(tr.transform(
1591 layer->visibleNonTransparentRegion));
1592 drawRegion.andSelf(bounds);
1593 if (!drawRegion.isEmpty()) {
1594 layersSortedByZ.add(layer);
1595 } else {
1596 // Clear out the HWC layer if this layer was
1597 // previously visible, but no longer is
1598 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1599 nullptr);
1600 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001601 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001602 // WM changes displayDevice->layerStack upon sleep/awake.
1603 // Here we make sure we delete the HWC layers even if
1604 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001605 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1606 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001607 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001608 });
1609 }
1610 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1611 displayDevice->undefinedRegion.set(bounds);
1612 displayDevice->undefinedRegion.subtractSelf(
1613 tr.transform(opaqueRegion));
1614 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001615 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001616 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001618
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001619// pickColorMode translates a given dataspace into the best available color mode.
1620// Currently only support sRGB and Display-P3.
1621android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1622 switch (dataSpace) {
1623 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1624 // system expects.
1625 case HAL_DATASPACE_UNKNOWN:
1626 case HAL_DATASPACE_SRGB:
1627 case HAL_DATASPACE_V0_SRGB:
1628 return HAL_COLOR_MODE_SRGB;
1629 break;
1630
1631 case HAL_DATASPACE_DISPLAY_P3:
1632 return HAL_COLOR_MODE_DISPLAY_P3;
1633 break;
1634
1635 default:
1636 // TODO (courtneygo): Do we want to assert an error here?
1637 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1638 dataSpace);
1639 return HAL_COLOR_MODE_SRGB;
1640 break;
1641 }
1642}
1643
1644android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1645 // Only support sRGB and Display-P3 right now.
1646 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1647 return HAL_DATASPACE_DISPLAY_P3;
1648 }
1649 return HAL_DATASPACE_V0_SRGB;
1650}
1651
Mathias Agopiancd60f992012-08-16 16:28:27 -07001652void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001653 ATRACE_CALL();
1654 ALOGV("setUpHWComposer");
1655
Jesse Hall028dc8f2013-08-20 16:35:32 -07001656 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001657 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1658 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1659 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1660
1661 // If nothing has changed (!dirty), don't recompose.
1662 // If something changed, but we don't currently have any visible layers,
1663 // and didn't when we last did a composition, then skip it this time.
1664 // The second rule does two things:
1665 // - When all layers are removed from a display, we'll emit one black
1666 // frame, then nothing more until we get new layers.
1667 // - When a display is created with a private layer stack, we won't
1668 // emit any black frames until a layer is added to the layer stack.
1669 bool mustRecompose = dirty && !(empty && wasEmpty);
1670
1671 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1672 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1673 mustRecompose ? "doing" : "skipping",
1674 dirty ? "+" : "-",
1675 empty ? "+" : "-",
1676 wasEmpty ? "+" : "-");
1677
Dan Stoza71433162014-02-04 16:22:36 -08001678 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001679
1680 if (mustRecompose) {
1681 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1682 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001683 }
1684
Dan Stoza9e56aa02015-11-02 13:00:03 -08001685 // build the h/w work list
1686 if (CC_UNLIKELY(mGeometryInvalid)) {
1687 mGeometryInvalid = false;
1688 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1689 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1690 const auto hwcId = displayDevice->getHwcDisplayId();
1691 if (hwcId >= 0) {
1692 const Vector<sp<Layer>>& currentLayers(
1693 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001694 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001695 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 if (!layer->hasHwcLayer(hwcId)) {
1697 auto hwcLayer = mHwc->createLayer(hwcId);
1698 if (hwcLayer) {
1699 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1700 } else {
1701 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001703 }
1704 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001705
Robert Carrae060832016-11-28 10:51:00 -08001706 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001707 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001708 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001709 }
1710 }
1711 }
1712 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001713 }
Riley Andrews03414a12014-07-01 14:22:59 -07001714
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001715
1716 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1717
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 // Set the per-frame data
1719 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1720 auto& displayDevice = mDisplays[displayId];
1721 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001722
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 if (hwcId < 0) {
1724 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001725 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001726 if (colorMatrix != mPreviousColorMatrix) {
1727 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1728 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1729 "display %zd: %d", displayId, result);
1730 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001731 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1732 layer->setPerFrameData(displayDevice);
1733 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001734
1735 if (hasWideColorDisplay) {
1736 android_color_mode newColorMode;
1737 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1738
1739 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1740 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1741 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1742 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1743 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1744 }
1745 newColorMode = pickColorMode(newDataSpace);
1746
1747 setActiveColorModeInternal(displayDevice, newColorMode);
1748 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 }
1750
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001751 mPreviousColorMatrix = colorMatrix;
1752
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001754 auto& displayDevice = mDisplays[displayId];
1755 if (!displayDevice->isDisplayOn()) {
1756 continue;
1757 }
1758
1759 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1761 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001762 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001764
Mathias Agopiancd60f992012-08-16 16:28:27 -07001765void SurfaceFlinger::doComposition() {
1766 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 ALOGV("doComposition");
1768
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001769 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001770 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001771 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001772 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773 // transform the dirty region into this screen's coordinate space
1774 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001775
1776 // repaint the framebuffer (if needed)
1777 doDisplayComposition(hw, dirtyRegion);
1778
Mathias Agopiancd60f992012-08-16 16:28:27 -07001779 hw->dirtyRegion.clear();
1780 hw->flip(hw->swapRegion);
1781 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001782 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001783 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001784 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001785}
1786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001787void SurfaceFlinger::postFramebuffer()
1788{
Mathias Agopian841cde52012-03-01 15:44:37 -08001789 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001790 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001791
Mathias Agopiana44b0412011-10-16 18:46:35 -07001792 const nsecs_t now = systemTime();
1793 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001794
Dan Stoza9e56aa02015-11-02 13:00:03 -08001795 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1796 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001797 if (!displayDevice->isDisplayOn()) {
1798 continue;
1799 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 const auto hwcId = displayDevice->getHwcDisplayId();
1801 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001802 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001803 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001804 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001805 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1807 sp<Fence> releaseFence = Fence::NO_FENCE;
1808 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1809 releaseFence = displayDevice->getClientTargetAcquireFence();
1810 } else {
1811 auto hwcLayer = layer->getHwcLayer(hwcId);
1812 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001813 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 layer->onLayerDisplayed(releaseFence);
1815 }
1816 if (hwcId >= 0) {
1817 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001818 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001819 }
1820
Mathias Agopiana44b0412011-10-16 18:46:35 -07001821 mLastSwapBufferTime = systemTime() - now;
1822 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001823
Polina Bondarenko80c02322017-04-10 10:15:42 +00001824 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001825 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1826 logFrameStats();
1827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828}
1829
Mathias Agopian87baae12012-07-31 12:38:26 -07001830void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831{
Mathias Agopian841cde52012-03-01 15:44:37 -08001832 ATRACE_CALL();
1833
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001834 // here we keep a copy of the drawing state (that is the state that's
1835 // going to be overwritten by handleTransactionLocked()) outside of
1836 // mStateLock so that the side-effects of the State assignment
1837 // don't happen with mStateLock held (which can cause deadlocks).
1838 State drawingState(mDrawingState);
1839
Mathias Agopianca4d3602011-05-19 15:38:14 -07001840 Mutex::Autolock _l(mStateLock);
1841 const nsecs_t now = systemTime();
1842 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001843
Mathias Agopianca4d3602011-05-19 15:38:14 -07001844 // Here we're guaranteed that some transaction flags are set
1845 // so we can call handleTransactionLocked() unconditionally.
1846 // We call getTransactionFlags(), which will also clear the flags,
1847 // with mStateLock held to guarantee that mCurrentState won't change
1848 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001849
Mathias Agopiane57f2922012-08-09 16:29:12 -07001850 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001851 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001852
Mathias Agopianca4d3602011-05-19 15:38:14 -07001853 mLastTransactionTime = systemTime() - now;
1854 mDebugInTransaction = 0;
1855 invalidateHwcGeometry();
1856 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001857}
1858
Mathias Agopian87baae12012-07-31 12:38:26 -07001859void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001860{
Dan Stoza7dde5992015-05-22 09:51:44 -07001861 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mCurrentState.traverseInZOrder([](Layer* layer) {
1863 layer->notifyAvailableFrames();
1864 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866 /*
1867 * Traversal of the children
1868 * (perform the transaction for each of them if needed)
1869 */
1870
Mathias Agopian3559b072012-08-15 13:46:03 -07001871 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001872 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001873 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001874 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875
1876 const uint32_t flags = layer->doTransaction(0);
1877 if (flags & Layer::eVisibleRegion)
1878 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001879 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001880 }
1881
1882 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001883 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001884 */
1885
Mathias Agopiane57f2922012-08-09 16:29:12 -07001886 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001887 // here we take advantage of Vector's copy-on-write semantics to
1888 // improve performance by skipping the transaction entirely when
1889 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001890 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1891 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001892 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001894 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001895 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001896
1897 // find the displays that were removed
1898 // (ie: in drawing state but not in current state)
1899 // also handle displays that changed
1900 // (ie: displays that are in both lists)
1901 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001902 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1903 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001904 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001905 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001906 // Call makeCurrent() on the primary display so we can
1907 // be sure that nothing associated with this display
1908 // is current.
Polina Bondarenko80c02322017-04-10 10:15:42 +00001909 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001910 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001911 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1912 if (hw != NULL)
1913 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001914 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001915 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001916 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001917 } else {
1918 ALOGW("trying to remove the main display");
1919 }
1920 } else {
1921 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001922 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001923 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001924 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1925 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001926 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001927 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001928 // recreating the DisplayDevice, so we just remove it
1929 // from the drawing state, so that it get re-added
1930 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001931 sp<DisplayDevice> hw(getDisplayDevice(display));
1932 if (hw != NULL)
1933 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001934 mDisplays.removeItem(display);
1935 mDrawingState.displays.removeItemsAt(i);
1936 dc--; i--;
1937 // at this point we must loop to the next item
1938 continue;
1939 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001940
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001941 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001942 if (disp != NULL) {
1943 if (state.layerStack != draw[i].layerStack) {
1944 disp->setLayerStack(state.layerStack);
1945 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001946 if ((state.orientation != draw[i].orientation)
1947 || (state.viewport != draw[i].viewport)
1948 || (state.frame != draw[i].frame))
1949 {
1950 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001951 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001952 }
Michael Lentine47e45402014-07-18 15:34:25 -07001953 if (state.width != draw[i].width || state.height != draw[i].height) {
1954 disp->setDisplaySize(state.width, state.height);
1955 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001956 }
1957 }
1958 }
1959
1960 // find displays that were added
1961 // (ie: in current state but not in drawing state)
1962 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001963 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001964 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001965
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001966 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001967 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001968 sp<IGraphicBufferProducer> bqProducer;
1969 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001970 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1971 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001972
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001974 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001975 // Virtual displays without a surface are dormant:
1976 // they have external state (layer stack, projection,
1977 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001978 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001979
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04001980 // Allow VR composer to use virtual displays.
1981 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07001982 int width = 0;
1983 int status = state.surface->query(
1984 NATIVE_WINDOW_WIDTH, &width);
1985 ALOGE_IF(status != NO_ERROR,
1986 "Unable to query width (%d)", status);
1987 int height = 0;
1988 status = state.surface->query(
1989 NATIVE_WINDOW_HEIGHT, &height);
1990 ALOGE_IF(status != NO_ERROR,
1991 "Unable to query height (%d)", status);
1992 int intFormat = 0;
1993 status = state.surface->query(
1994 NATIVE_WINDOW_FORMAT, &intFormat);
1995 ALOGE_IF(status != NO_ERROR,
1996 "Unable to query format (%d)", status);
1997 auto format = static_cast<android_pixel_format_t>(
1998 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001999
Dan Stoza8cf150a2016-08-02 10:27:31 -07002000 mHwc->allocateVirtualDisplay(width, height, &format,
2001 &hwcId);
2002 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003
Dan Stoza5cf424b2016-05-20 14:02:39 -07002004 // TODO: Plumb requested format back up to consumer
2005
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 sp<VirtualDisplaySurface> vds =
2007 new VirtualDisplaySurface(*mHwc,
2008 hwcId, state.surface, bqProducer,
2009 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002010
2011 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002012 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002013 }
2014 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002015 ALOGE_IF(state.surface!=NULL,
2016 "adding a supported display, but rendering "
2017 "surface is provided (%p), ignoring it",
2018 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002019
2020 hwcId = state.type;
2021 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2022 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002023 }
2024
2025 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002026 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002027 sp<DisplayDevice> hw =
2028 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2029 dispSurface, producer,
2030 mRenderEngine->getEGLConfig(),
2031 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002032 hw->setLayerStack(state.layerStack);
2033 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002034 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002035 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002036 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002038 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002039 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002040 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002041 }
2042 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002044 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045
Mathias Agopian84300952012-11-21 16:02:13 -08002046 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2047 // The transform hint might have changed for some layers
2048 // (either because a display has changed, or because a layer
2049 // as changed).
2050 //
2051 // Walk through all the layers in currentLayers,
2052 // and update their transform hint.
2053 //
2054 // If a layer is visible only on a single display, then that
2055 // display is used to calculate the hint, otherwise we use the
2056 // default display.
2057 //
2058 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2059 // the hint is set before we acquire a buffer from the surface texture.
2060 //
2061 // NOTE: layer transactions have taken place already, so we use their
2062 // drawing state. However, SurfaceFlinger's own transaction has not
2063 // happened yet, so we must use the current state layer list
2064 // (soon to become the drawing state list).
2065 //
2066 sp<const DisplayDevice> disp;
2067 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002068 bool first = true;
2069 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002070 // NOTE: we rely on the fact that layers are sorted by
2071 // layerStack first (so we don't have to traverse the list
2072 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002073 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002074 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002075 currentlayerStack = layerStack;
2076 // figure out if this layerstack is mirrored
2077 // (more than one display) if so, pick the default display,
2078 // if not, pick the only display it's on.
2079 disp.clear();
2080 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2081 sp<const DisplayDevice> hw(mDisplays[dpy]);
2082 if (hw->getLayerStack() == currentlayerStack) {
2083 if (disp == NULL) {
2084 disp = hw;
2085 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002086 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002087 break;
2088 }
2089 }
2090 }
2091 }
Chet Haase91d25932013-04-11 15:24:55 -07002092 if (disp == NULL) {
2093 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2094 // redraw after transform hint changes. See bug 8508397.
2095
2096 // could be null when this layer is using a layerStack
2097 // that is not visible on any display. Also can occur at
2098 // screen off/on times.
Polina Bondarenko80c02322017-04-10 10:15:42 +00002099 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002100 }
Chet Haase91d25932013-04-11 15:24:55 -07002101 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002102
2103 first = false;
2104 });
Mathias Agopian84300952012-11-21 16:02:13 -08002105 }
2106
2107
Mathias Agopian3559b072012-08-15 13:46:03 -07002108 /*
2109 * Perform our own transaction if needed
2110 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002111
2112 if (mLayersAdded) {
2113 mLayersAdded = false;
2114 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002115 mVisibleRegionsDirty = true;
2116 }
2117
2118 // some layers might have been removed, so
2119 // we need to update the regions they're exposing.
2120 if (mLayersRemoved) {
2121 mLayersRemoved = false;
2122 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002123 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002124 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002125 // this layer is not visible anymore
2126 // TODO: we could traverse the tree from front to back and
2127 // compute the actual visible region
2128 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002129 Region visibleReg;
2130 visibleReg.set(layer->computeScreenBounds());
2131 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002132 }
Robert Carr2047fae2016-11-28 14:09:09 -08002133 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134 }
2135
2136 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002137
2138 updateCursorAsync();
2139}
2140
2141void SurfaceFlinger::updateCursorAsync()
2142{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2144 auto& displayDevice = mDisplays[displayId];
2145 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002146 continue;
2147 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148
2149 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2150 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002151 }
2152 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002153}
2154
2155void SurfaceFlinger::commitTransaction()
2156{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002157 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002158 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002159 for (const auto& l : mLayersPendingRemoval) {
2160 recordBufferingStats(l->getName().string(),
2161 l->getOccupancyHistory(true));
2162 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002163 }
2164 mLayersPendingRemoval.clear();
2165 }
2166
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002167 // If this transaction is part of a window animation then the next frame
2168 // we composite should be considered an animation as well.
2169 mAnimCompositionPending = mAnimTransactionPending;
2170
Mathias Agopian4fec8732012-06-29 14:12:52 -07002171 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002172 mDrawingState.traverseInZOrder([](Layer* layer) {
2173 layer->commitChildList();
2174 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002175 mTransactionPending = false;
2176 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002177 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178}
2179
Robert Carr2047fae2016-11-28 14:09:09 -08002180void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002181 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002182{
Mathias Agopian841cde52012-03-01 15:44:37 -08002183 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186 Region aboveOpaqueLayers;
2187 Region aboveCoveredLayers;
2188 Region dirty;
2189
Mathias Agopian87baae12012-07-31 12:38:26 -07002190 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002191
Robert Carr2047fae2016-11-28 14:09:09 -08002192 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002193 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002194 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002195
Jesse Hall01e29052013-02-19 16:13:35 -08002196 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002197 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002198 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002199
Mathias Agopianab028732010-03-16 16:41:46 -07002200 /*
2201 * opaqueRegion: area of a surface that is fully opaque.
2202 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002204
2205 /*
2206 * visibleRegion: area of a surface that is visible on screen
2207 * and not fully transparent. This is essentially the layer's
2208 * footprint minus the opaque regions above it.
2209 * Areas covered by a translucent surface are considered visible.
2210 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002211 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002212
2213 /*
2214 * coveredRegion: area of a surface that is covered by all
2215 * visible regions above it (which includes the translucent areas).
2216 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002218
Jesse Halla8026d22012-09-25 13:25:04 -07002219 /*
2220 * transparentRegion: area of a surface that is hinted to be completely
2221 * transparent. This is only used to tell when the layer has no visible
2222 * non-transparent regions and can be removed from the layer list. It
2223 * does not affect the visibleRegion of this layer or any layers
2224 * beneath it. The hint may not be correct if apps don't respect the
2225 * SurfaceView restrictions (which, sadly, some don't).
2226 */
2227 Region transparentRegion;
2228
Mathias Agopianab028732010-03-16 16:41:46 -07002229
2230 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002231 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002232 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002233 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002235 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002236 if (!visibleRegion.isEmpty()) {
2237 // Remove the transparent area from the visible region
2238 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002239 if (tr.preserveRects()) {
2240 // transform the transparent region
2241 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002242 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002243 // transformation too complex, can't do the
2244 // transparent region optimization.
2245 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002246 }
Mathias Agopianab028732010-03-16 16:41:46 -07002247 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248
Mathias Agopianab028732010-03-16 16:41:46 -07002249 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002250 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002251 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002252 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2253 // the opaque region is the layer's footprint
2254 opaqueRegion = visibleRegion;
2255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256 }
2257 }
2258
Mathias Agopianab028732010-03-16 16:41:46 -07002259 // Clip the covered region to the visible region
2260 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2261
2262 // Update aboveCoveredLayers for next (lower) layer
2263 aboveCoveredLayers.orSelf(visibleRegion);
2264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002265 // subtract the opaque region covered by the layers above us
2266 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002267
2268 // compute this layer's dirty region
2269 if (layer->contentDirty) {
2270 // we need to invalidate the whole region
2271 dirty = visibleRegion;
2272 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002273 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002274 layer->contentDirty = false;
2275 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002276 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002277 * the exposed region consists of two components:
2278 * 1) what's VISIBLE now and was COVERED before
2279 * 2) what's EXPOSED now less what was EXPOSED before
2280 *
2281 * note that (1) is conservative, we start with the whole
2282 * visible region but only keep what used to be covered by
2283 * something -- which mean it may have been exposed.
2284 *
2285 * (2) handles areas that were not covered by anything but got
2286 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002287 */
Mathias Agopianab028732010-03-16 16:41:46 -07002288 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002289 const Region oldVisibleRegion = layer->visibleRegion;
2290 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002291 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2292 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002293 }
2294 dirty.subtractSelf(aboveOpaqueLayers);
2295
2296 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002297 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298
Mathias Agopianab028732010-03-16 16:41:46 -07002299 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002301
Jesse Halla8026d22012-09-25 13:25:04 -07002302 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303 layer->setVisibleRegion(visibleRegion);
2304 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002305 layer->setVisibleNonTransparentRegion(
2306 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002307 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308
Mathias Agopian87baae12012-07-31 12:38:26 -07002309 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310}
2311
Mathias Agopian87baae12012-07-31 12:38:26 -07002312void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2313 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002314 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002315 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2316 if (hw->getLayerStack() == layerStack) {
2317 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002318 }
2319 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002320}
2321
Dan Stoza6b9454d2014-11-07 16:00:59 -08002322bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002323{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002324 ALOGV("handlePageFlip");
2325
Brian Andersond6927fb2016-07-23 23:37:30 -07002326 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327
Mathias Agopian4fec8732012-06-29 14:12:52 -07002328 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002329 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002330
2331 // Store the set of layers that need updates. This set must not change as
2332 // buffers are being latched, as this could result in a deadlock.
2333 // Example: Two producers share the same command stream and:
2334 // 1.) Layer 0 is latched
2335 // 2.) Layer 0 gets a new frame
2336 // 2.) Layer 1 gets a new frame
2337 // 3.) Layer 1 is latched.
2338 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2339 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002340 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002341 if (layer->hasQueuedFrame()) {
2342 frameQueued = true;
2343 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002344 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002345 } else {
2346 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002347 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002348 } else {
2349 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002350 }
Robert Carr2047fae2016-11-28 14:09:09 -08002351 });
2352
Dan Stoza9e56aa02015-11-02 13:00:03 -08002353 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002354 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002355 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002356 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002357 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002358
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002359 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002360
2361 // If we will need to wake up at some time in the future to deal with a
2362 // queued frame that shouldn't be displayed during this vsync period, wake
2363 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002364 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002365 signalLayerUpdate();
2366 }
2367
2368 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002369 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370}
2371
Mathias Agopianad456f92011-01-13 17:53:01 -08002372void SurfaceFlinger::invalidateHwcGeometry()
2373{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002374 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002375}
2376
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002377
Fabien Sanglard830b8472016-11-30 16:35:58 -08002378void SurfaceFlinger::doDisplayComposition(
2379 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002380 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381{
Dan Stoza71433162014-02-04 16:22:36 -08002382 // We only need to actually compose the display if:
2383 // 1) It is being handled by hardware composer, which may need this to
2384 // keep its virtual display state machine in sync, or
2385 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002386 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002387 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002389 return;
2390 }
2391
Dan Stoza9e56aa02015-11-02 13:00:03 -08002392 ALOGV("doDisplayComposition");
2393
Mathias Agopian87baae12012-07-31 12:38:26 -07002394 Region dirtyRegion(inDirtyRegion);
2395
Mathias Agopianb8a55602009-06-26 19:06:36 -07002396 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002397 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398
Fabien Sanglard830b8472016-11-30 16:35:58 -08002399 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002400 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002401 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2402 // takes a rectangle, we must make sure to update that whole
2403 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002404 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002405 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002406 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002407 // We need to redraw the rectangle that will be updated
2408 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002409 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002410 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002411 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002412 } else {
2413 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002414 dirtyRegion.set(displayDevice->bounds());
2415 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002416 }
2417 }
2418
Fabien Sanglard830b8472016-11-30 16:35:58 -08002419 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002421 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002422 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002423
2424 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002425 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426}
2427
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428bool SurfaceFlinger::doComposeSurfaces(
2429 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002430{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002431 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002432
Dan Stoza9e56aa02015-11-02 13:00:03 -08002433 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002434
2435 mat4 oldColorMatrix;
2436 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2437 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2438 if (applyColorMatrix) {
2439 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2440 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2441 }
2442
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2444 if (hasClientComposition) {
2445 ALOGV("hasClientComposition");
2446
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002447#ifdef USE_HWC2
2448 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2449 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2450#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002452 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002454 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Polina Bondarenko80c02322017-04-10 10:15:42 +00002455 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002456 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2457 }
2458 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002459 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002460
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002461 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2463 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002464 // when using overlays, we assume a fully transparent framebuffer
2465 // NOTE: we could reduce how much we need to clear, for instance
2466 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002467 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002468 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002470 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002471 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002473
2474 // we remove the scissor part
2475 // we're left with the letterbox region
2476 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002478
2479 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002481
2482 // but limit it to the dirty region
2483 region.andSelf(dirty);
2484
Mathias Agopianb9494d52012-04-18 02:28:45 -07002485 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002486 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002487 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002489 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002490 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002491
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002493 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002494 // scissor on the main display. It should never be needed
2495 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 const Rect& bounds(displayDevice->getBounds());
2497 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002498 if (scissor != bounds) {
2499 // scissor doesn't match the screen's dimensions, so we
2500 // need to clear everything outside of it and enable
2501 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002502
Mathias Agopianf45c5102012-10-24 16:29:17 -07002503 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 const uint32_t height = displayDevice->getHeight();
2505 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002506 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002507 }
2508 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002509 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002510
Mathias Agopian85d751c2012-08-29 16:59:24 -07002511 /*
2512 * and then, render the layers targeted at the framebuffer
2513 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002514
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 ALOGV("Rendering client layers");
2516 const Transform& displayTransform = displayDevice->getTransform();
2517 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002518 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 bool firstLayer = true;
2520 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2521 const Region clip(dirty.intersect(
2522 displayTransform.transform(layer->visibleRegion)));
2523 ALOGV("Layer: %s", layer->getName().string());
2524 ALOGV(" Composition type: %s",
2525 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002526 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 switch (layer->getCompositionType(hwcId)) {
2528 case HWC2::Composition::Cursor:
2529 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002530 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002532 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2534 layer->isOpaque(state) && (state.alpha == 1.0f)
2535 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002536 // never clear the very first layer since we're
2537 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002538 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002539 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002540 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002541 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 case HWC2::Composition::Client: {
2543 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002544 break;
2545 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002547 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002548 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 } else {
2550 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002551 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002552 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002553 }
2554 } else {
2555 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002557 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002559 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002561 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002562 }
2563 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002564
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002565 if (applyColorMatrix) {
2566 getRenderEngine().setupColorTransform(oldColorMatrix);
2567 }
2568
Mathias Agopianf45c5102012-10-24 16:29:17 -07002569 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002570 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002571 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572}
2573
Fabien Sanglard830b8472016-11-30 16:35:58 -08002574void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2575 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002576 RenderEngine& engine(getRenderEngine());
2577 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578}
2579
Dan Stoza7d89d062015-04-30 13:29:25 -07002580status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002581 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002582 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002583 const sp<Layer>& lbc,
2584 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002585{
Dan Stoza7d89d062015-04-30 13:29:25 -07002586 // add this layer to the current state list
2587 {
2588 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002589 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002590 return NO_MEMORY;
2591 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002592 if (parent == nullptr) {
2593 mCurrentState.layersSortedByZ.add(lbc);
2594 } else {
2595 parent->addChild(lbc);
2596 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002597 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002598 mLayersAdded = true;
2599 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002600 }
2601
Mathias Agopian96f08192010-06-02 23:28:45 -07002602 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002603 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002604
Dan Stoza7d89d062015-04-30 13:29:25 -07002605 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002606}
2607
Robert Carr9524cb32017-02-13 11:32:32 -08002608status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002609 Mutex::Autolock _l(mStateLock);
2610
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 const auto& p = layer->getParent();
2612 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2613 mCurrentState.layersSortedByZ.remove(layer);
2614
Robert Carr136e2f62017-02-08 17:54:29 -08002615 // As a matter of normal operation, the LayerCleaner will produce a second
2616 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2617 // so we will succeed in promoting it, but it's already been removed
2618 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2619 // otherwise something has gone wrong and we are leaking the layer.
2620 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002621 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2622 layer->getName().string(),
2623 (p != nullptr) ? p->getName().string() : "no-parent");
2624 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002625 } else if (index < 0) {
2626 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002627 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002628
2629 mLayersPendingRemoval.add(layer);
2630 mLayersRemoved = true;
2631 mNumLayers--;
2632 setTransactionFlags(eTransactionNeeded);
2633 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634}
2635
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002636uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002637 return android_atomic_release_load(&mTransactionFlags);
2638}
2639
Mathias Agopian3f844832013-08-07 21:24:32 -07002640uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2642}
2643
Mathias Agopian3f844832013-08-07 21:24:32 -07002644uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2646 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002647 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648 }
2649 return old;
2650}
2651
Mathias Agopian8b33f032012-07-24 20:43:54 -07002652void SurfaceFlinger::setTransactionState(
2653 const Vector<ComposerState>& state,
2654 const Vector<DisplayState>& displays,
2655 uint32_t flags)
2656{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002657 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002658 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002659 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002660
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002661 if (flags & eAnimation) {
2662 // For window updates that are part of an animation we must wait for
2663 // previous animation "frames" to be handled.
2664 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002665 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002666 if (CC_UNLIKELY(err != NO_ERROR)) {
2667 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002668 // caller after a few seconds.
2669 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2670 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002671 mAnimTransactionPending = false;
2672 break;
2673 }
2674 }
2675 }
2676
Mathias Agopiane57f2922012-08-09 16:29:12 -07002677 size_t count = displays.size();
2678 for (size_t i=0 ; i<count ; i++) {
2679 const DisplayState& s(displays[i]);
2680 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002681 }
2682
Mathias Agopiane57f2922012-08-09 16:29:12 -07002683 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002684 for (size_t i=0 ; i<count ; i++) {
2685 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002686 // Here we need to check that the interface we're given is indeed
2687 // one of our own. A malicious client could give us a NULL
2688 // IInterface, or one of its own or even one of our own but a
2689 // different type. All these situations would cause us to crash.
2690 //
2691 // NOTE: it would be better to use RTTI as we could directly check
2692 // that we have a Client*. however, RTTI is disabled in Android.
2693 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002694 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002695 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002696 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002697 sp<Client> client( static_cast<Client *>(s.client.get()) );
2698 transactionFlags |= setClientStateLocked(client, s.state);
2699 }
2700 }
2701 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002702 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002703
Robert Carr2a7dbb42016-05-24 11:41:28 -07002704 // If a synchronous transaction is explicitly requested without any changes,
2705 // force a transaction anyway. This can be used as a flush mechanism for
2706 // previous async transactions.
2707 if (transactionFlags == 0 && (flags & eSynchronous)) {
2708 transactionFlags = eTransactionNeeded;
2709 }
2710
Mathias Agopian386aa982011-11-07 21:58:03 -08002711 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002712 if (mInterceptor.isEnabled()) {
2713 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2714 }
Irvel468051e2016-06-13 16:44:44 -07002715
Mathias Agopian386aa982011-11-07 21:58:03 -08002716 // this triggers the transaction
2717 setTransactionFlags(transactionFlags);
2718
2719 // if this is a synchronous transaction, wait for it to take effect
2720 // before returning.
2721 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002722 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002723 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002724 if (flags & eAnimation) {
2725 mAnimTransactionPending = true;
2726 }
2727 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002728 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2729 if (CC_UNLIKELY(err != NO_ERROR)) {
2730 // just in case something goes wrong in SF, return to the
2731 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002732 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2733 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002734 break;
2735 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002736 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 }
2738}
2739
Mathias Agopiane57f2922012-08-09 16:29:12 -07002740uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2741{
Jesse Hall9a143922012-10-04 16:29:19 -07002742 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2743 if (dpyIdx < 0)
2744 return 0;
2745
Mathias Agopiane57f2922012-08-09 16:29:12 -07002746 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002747 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002748 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002749 const uint32_t what = s.what;
2750 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002751 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002752 disp.surface = s.surface;
2753 flags |= eDisplayTransactionNeeded;
2754 }
2755 }
2756 if (what & DisplayState::eLayerStackChanged) {
2757 if (disp.layerStack != s.layerStack) {
2758 disp.layerStack = s.layerStack;
2759 flags |= eDisplayTransactionNeeded;
2760 }
2761 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002762 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002763 if (disp.orientation != s.orientation) {
2764 disp.orientation = s.orientation;
2765 flags |= eDisplayTransactionNeeded;
2766 }
2767 if (disp.frame != s.frame) {
2768 disp.frame = s.frame;
2769 flags |= eDisplayTransactionNeeded;
2770 }
2771 if (disp.viewport != s.viewport) {
2772 disp.viewport = s.viewport;
2773 flags |= eDisplayTransactionNeeded;
2774 }
2775 }
Michael Lentine47e45402014-07-18 15:34:25 -07002776 if (what & DisplayState::eDisplaySizeChanged) {
2777 if (disp.width != s.width) {
2778 disp.width = s.width;
2779 flags |= eDisplayTransactionNeeded;
2780 }
2781 if (disp.height != s.height) {
2782 disp.height = s.height;
2783 flags |= eDisplayTransactionNeeded;
2784 }
2785 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002786 }
2787 return flags;
2788}
2789
2790uint32_t SurfaceFlinger::setClientStateLocked(
2791 const sp<Client>& client,
2792 const layer_state_t& s)
2793{
2794 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002795 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002796 if (layer != 0) {
2797 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002798 bool geometryAppliesWithResize =
2799 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002800 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002801 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002802 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002803 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002804 }
2805 if (what & layer_state_t::eLayerChanged) {
2806 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 const auto& p = layer->getParent();
2808 if (p == nullptr) {
2809 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2810 if (layer->setLayer(s.z) && idx >= 0) {
2811 mCurrentState.layersSortedByZ.removeAt(idx);
2812 mCurrentState.layersSortedByZ.add(layer);
2813 // we need traversal (state changed)
2814 // AND transaction (list changed)
2815 flags |= eTransactionNeeded|eTraversalNeeded;
2816 }
2817 } else {
2818 if (p->setChildLayer(layer, s.z)) {
2819 flags |= eTransactionNeeded|eTraversalNeeded;
2820 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002821 }
2822 }
2823 if (what & layer_state_t::eSizeChanged) {
2824 if (layer->setSize(s.w, s.h)) {
2825 flags |= eTraversalNeeded;
2826 }
2827 }
2828 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002829 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002830 flags |= eTraversalNeeded;
2831 }
2832 if (what & layer_state_t::eMatrixChanged) {
2833 if (layer->setMatrix(s.matrix))
2834 flags |= eTraversalNeeded;
2835 }
2836 if (what & layer_state_t::eTransparentRegionChanged) {
2837 if (layer->setTransparentRegionHint(s.transparentRegion))
2838 flags |= eTraversalNeeded;
2839 }
Dan Stoza23116082015-06-18 14:58:39 -07002840 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002841 if (layer->setFlags(s.flags, s.mask))
2842 flags |= eTraversalNeeded;
2843 }
2844 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002845 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002846 flags |= eTraversalNeeded;
2847 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002848 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002849 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002850 flags |= eTraversalNeeded;
2851 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002852 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002853 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002854 // We only allow setting layer stacks for top level layers,
2855 // everything else inherits layer stack from its parent.
2856 if (layer->hasParent()) {
2857 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2858 layer->getName().string());
2859 } else if (idx < 0) {
2860 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2861 "that also does not appear in the top level layer list. Something"
2862 " has gone wrong.", layer->getName().string());
2863 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002864 mCurrentState.layersSortedByZ.removeAt(idx);
2865 mCurrentState.layersSortedByZ.add(layer);
2866 // we need traversal (state changed)
2867 // AND transaction (list changed)
2868 flags |= eTransactionNeeded|eTraversalNeeded;
2869 }
2870 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002871 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002872 if (s.barrierHandle != nullptr) {
2873 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2874 } else if (s.barrierGbp != nullptr) {
2875 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2876 if (authenticateSurfaceTextureLocked(gbp)) {
2877 const auto& otherLayer =
2878 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2879 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2880 } else {
2881 ALOGE("Attempt to defer transaction to to an"
2882 " unrecognized GraphicBufferProducer");
2883 }
2884 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002885 // We don't trigger a traversal here because if no other state is
2886 // changed, we don't want this to cause any more work
2887 }
Robert Carr1db73f62016-12-21 12:58:51 -08002888 if (what & layer_state_t::eReparentChildren) {
2889 if (layer->reparentChildren(s.reparentHandle)) {
2890 flags |= eTransactionNeeded|eTraversalNeeded;
2891 }
2892 }
Robert Carr9524cb32017-02-13 11:32:32 -08002893 if (what & layer_state_t::eDetachChildren) {
2894 layer->detachChildren();
2895 }
Robert Carrc3574f72016-03-24 12:19:32 -07002896 if (what & layer_state_t::eOverrideScalingModeChanged) {
2897 layer->setOverrideScalingMode(s.overrideScalingMode);
2898 // We don't trigger a traversal here because if no other state is
2899 // changed, we don't want this to cause any more work
2900 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002901 }
2902 return flags;
2903}
2904
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002905status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002906 const String8& name,
2907 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002908 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002909 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2910 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002912 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002913 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002914 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002915 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002916 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002917
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002918 status_t result = NO_ERROR;
2919
2920 sp<Layer> layer;
2921
Cody Northropbc755282017-03-31 12:00:08 -06002922 String8 uniqueName = getUniqueLayerName(name);
2923
Mathias Agopian3165cc22012-08-08 19:42:09 -07002924 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2925 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002926 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002927 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002928 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002930 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002931 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002932 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002933 handle, gbp, &layer);
2934 break;
2935 default:
2936 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002937 break;
2938 }
2939
Dan Stoza7d89d062015-04-30 13:29:25 -07002940 if (result != NO_ERROR) {
2941 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002943
Albert Chaulk479c60c2017-01-27 14:21:34 -05002944 layer->setInfo(windowType, ownerUid);
2945
Robert Carr1f0a16a2016-10-24 16:27:39 -07002946 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002947 if (result != NO_ERROR) {
2948 return result;
2949 }
Irvelffc9efc2016-07-27 15:16:37 -07002950 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002951
2952 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002953 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954}
2955
Cody Northropbc755282017-03-31 12:00:08 -06002956String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
2957{
2958 bool matchFound = true;
2959 uint32_t dupeCounter = 0;
2960
2961 // Tack on our counter whether there is a hit or not, so everyone gets a tag
2962 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
2963
2964 // Loop over layers until we're sure there is no matching name
2965 while (matchFound) {
2966 matchFound = false;
2967 mDrawingState.traverseInZOrder([&](Layer* layer) {
2968 if (layer->getName() == uniqueName) {
2969 matchFound = true;
2970 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
2971 }
2972 });
2973 }
2974
2975 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
2976
2977 return uniqueName;
2978}
2979
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002980status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2981 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2982 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983{
2984 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002985 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 case PIXEL_FORMAT_TRANSPARENT:
2987 case PIXEL_FORMAT_TRANSLUCENT:
2988 format = PIXEL_FORMAT_RGBA_8888;
2989 break;
2990 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002991 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 break;
2993 }
2994
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002995 *outLayer = new Layer(this, client, name, w, h, flags);
2996 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2997 if (err == NO_ERROR) {
2998 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002999 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003001
3002 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3003 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004}
3005
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003006status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3007 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3008 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003010 *outLayer = new LayerDim(this, client, name, w, h, flags);
3011 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003012 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003013 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003014}
3015
Mathias Agopianac9fa422013-02-11 16:40:36 -08003016status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017{
Robert Carr9524cb32017-02-13 11:32:32 -08003018 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003019 status_t err = NO_ERROR;
3020 sp<Layer> l(client->getLayerUser(handle));
3021 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003022 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003023 err = removeLayer(l);
3024 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3025 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003026 }
3027 return err;
3028}
3029
Mathias Agopian13127d82013-03-05 17:47:11 -08003030status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003031{
Mathias Agopian67106042013-03-14 19:18:13 -07003032 // called by ~LayerCleaner() when all references to the IBinder (handle)
3033 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003034 sp<Layer> l = layer.promote();
3035 if (l == nullptr) {
3036 // The layer has already been removed, carry on
3037 return NO_ERROR;
3038 } if (l->getParent() != nullptr) {
3039 // If we have a parent, then we can continue to live as long as it does.
3040 return NO_ERROR;
3041 }
3042 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043}
3044
Mathias Agopianb60314a2012-04-10 22:09:54 -07003045// ---------------------------------------------------------------------------
3046
Andy McFadden13a082e2012-08-24 10:16:42 -07003047void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003048 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003049 Vector<ComposerState> state;
3050 Vector<DisplayState> displays;
3051 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003052 d.what = DisplayState::eDisplayProjectionChanged |
3053 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003054 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003055 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003056 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003057 d.frame.makeInvalid();
3058 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003059 d.width = 0;
3060 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003061 displays.add(d);
3062 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003063 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003064
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3066 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003067 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003068
Brian Andersond0010582017-03-07 13:20:31 -08003069 // Use phase of 0 since phase is not known.
3070 // Use latency of 0, which will snap to the ideal latency.
3071 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003072}
3073
3074void SurfaceFlinger::initializeDisplays() {
3075 class MessageScreenInitialized : public MessageBase {
3076 SurfaceFlinger* flinger;
3077 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003078 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003079 virtual bool handler() {
3080 flinger->onInitializeDisplays();
3081 return true;
3082 }
3083 };
3084 sp<MessageBase> msg = new MessageScreenInitialized(this);
3085 postMessageAsync(msg); // we may be called from main thread, use async message
3086}
3087
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003088void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3089 int mode) {
3090 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3091 this);
3092 int32_t type = hw->getDisplayType();
3093 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003094
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003095 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003096 return;
3097 }
3098
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003099 hw->setPowerMode(mode);
3100 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3101 ALOGW("Trying to set power mode for virtual display");
3102 return;
3103 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003104
Irvelffc9efc2016-07-27 15:16:37 -07003105 if (mInterceptor.isEnabled()) {
3106 Mutex::Autolock _l(mStateLock);
3107 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3108 if (idx < 0) {
3109 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3110 return;
3111 }
3112 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3113 }
3114
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003115 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003116 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003117 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003118 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3119 // FIXME: eventthread only knows about the main display right now
3120 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003121 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003122 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003124 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003125 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003126 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003127
3128 struct sched_param param = {0};
3129 param.sched_priority = 1;
3130 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3131 ALOGW("Couldn't set SCHED_FIFO on display on");
3132 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003133 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003134 // Turn off the display
3135 struct sched_param param = {0};
3136 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3137 ALOGW("Couldn't set SCHED_OTHER on display off");
3138 }
3139
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003140 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003141 disableHardwareVsync(true); // also cancels any in-progress resync
3142
Mathias Agopiancde87a32012-09-13 14:09:01 -07003143 // FIXME: eventthread only knows about the main display right now
3144 mEventThread->onScreenReleased();
3145 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003146
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003147 getHwComposer().setPowerMode(type, mode);
3148 mVisibleRegionsDirty = true;
3149 // from this point on, SF will stop drawing on this display
3150 } else {
3151 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003152 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003153}
3154
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003155void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3156 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003157 SurfaceFlinger& mFlinger;
3158 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003159 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003160 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003161 MessageSetPowerMode(SurfaceFlinger& flinger,
3162 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3163 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003164 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003165 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003166 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003167 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003168 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003169 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003170 ALOGW("Attempt to set power mode = %d for virtual display",
3171 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003172 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003173 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003174 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003175 return true;
3176 }
3177 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003178 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003179 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003180}
3181
3182// ---------------------------------------------------------------------------
3183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3185{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003187
Mathias Agopianbd115332013-04-18 16:41:04 -07003188 IPCThreadState* ipc = IPCThreadState::self();
3189 const int pid = ipc->getCallingPid();
3190 const int uid = ipc->getCallingUid();
3191 if ((uid != AID_SHELL) &&
3192 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003193 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003194 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003196 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003197 // (this would indicate SF is stuck, but we want to be able to
3198 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003199 status_t err = mStateLock.timedLock(s2ns(1));
3200 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003201 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003202 result.appendFormat(
3203 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3204 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003205 }
3206
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003207 bool dumpAll = true;
3208 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003209 size_t numArgs = args.size();
3210 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003211 if ((index < numArgs) &&
3212 (args[index] == String16("--list"))) {
3213 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003214 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003215 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003216 }
3217
3218 if ((index < numArgs) &&
3219 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003220 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003221 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003222 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003223 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003224
3225 if ((index < numArgs) &&
3226 (args[index] == String16("--latency-clear"))) {
3227 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003228 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003229 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003230 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003231
3232 if ((index < numArgs) &&
3233 (args[index] == String16("--dispsync"))) {
3234 index++;
3235 mPrimaryDispSync.dump(result);
3236 dumpAll = false;
3237 }
Dan Stozab90cf072015-03-05 11:05:59 -08003238
3239 if ((index < numArgs) &&
3240 (args[index] == String16("--static-screen"))) {
3241 index++;
3242 dumpStaticScreenStats(result);
3243 dumpAll = false;
3244 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003245
3246 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003247 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003248 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003249 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003250 dumpAll = false;
3251 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003252
3253 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3254 index++;
3255 dumpWideColorInfo(result);
3256 dumpAll = false;
3257 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003259
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003260 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003261 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003262 }
3263
Mathias Agopian9795c422009-08-26 16:36:26 -07003264 if (locked) {
3265 mStateLock.unlock();
3266 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 write(fd, result.string(), result.size());
3269 return NO_ERROR;
3270}
3271
Dan Stozac7014012014-02-14 15:03:43 -08003272void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3273 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003274{
Robert Carr2047fae2016-11-28 14:09:09 -08003275 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003276 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003277 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003278}
3279
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003280void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003281 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003282{
3283 String8 name;
3284 if (index < args.size()) {
3285 name = String8(args[index]);
3286 index++;
3287 }
3288
Dan Stoza9e56aa02015-11-02 13:00:03 -08003289 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3290 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003291 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003292
3293 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003294 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003295 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003296 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003297 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003298 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003299 }
Robert Carr2047fae2016-11-28 14:09:09 -08003300 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003301 }
3302}
3303
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003304void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003305 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003306{
3307 String8 name;
3308 if (index < args.size()) {
3309 name = String8(args[index]);
3310 index++;
3311 }
3312
Robert Carr2047fae2016-11-28 14:09:09 -08003313 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003314 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003315 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003316 }
Robert Carr2047fae2016-11-28 14:09:09 -08003317 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003318
Svetoslavd85084b2014-03-20 10:28:31 -07003319 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003320}
3321
Jamie Gennis6547ff42013-07-16 20:12:42 -07003322// This should only be called from the main thread. Otherwise it would need
3323// the lock and should use mCurrentState rather than mDrawingState.
3324void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003325 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003326 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003327 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003328
3329 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3330}
3331
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003332void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003333{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003334 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003335 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3336
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003337 if (isLayerTripleBufferingDisabled())
3338 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003339
3340 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003341 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003342 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003343 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003344 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3345 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003346 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003347}
3348
Dan Stozab90cf072015-03-05 11:05:59 -08003349void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3350{
3351 result.appendFormat("Static screen stats:\n");
3352 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3353 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3354 float percent = 100.0f *
3355 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3356 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3357 b + 1, bucketTimeSec, percent);
3358 }
3359 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3360 float percent = 100.0f *
3361 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3362 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3363 NUM_BUCKETS - 1, bucketTimeSec, percent);
3364}
3365
Dan Stozae77c7662016-05-13 11:37:28 -07003366void SurfaceFlinger::recordBufferingStats(const char* layerName,
3367 std::vector<OccupancyTracker::Segment>&& history) {
3368 Mutex::Autolock lock(mBufferingStatsMutex);
3369 auto& stats = mBufferingStats[layerName];
3370 for (const auto& segment : history) {
3371 if (!segment.usedThirdBuffer) {
3372 stats.twoBufferTime += segment.totalTime;
3373 }
3374 if (segment.occupancyAverage < 1.0f) {
3375 stats.doubleBufferedTime += segment.totalTime;
3376 } else if (segment.occupancyAverage < 2.0f) {
3377 stats.tripleBufferedTime += segment.totalTime;
3378 }
3379 ++stats.numSegments;
3380 stats.totalTime += segment.totalTime;
3381 }
3382}
3383
Brian Andersond6927fb2016-07-23 23:37:30 -07003384void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3385 result.appendFormat("Layer frame timestamps:\n");
3386
3387 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3388 const size_t count = currentLayers.size();
3389 for (size_t i=0 ; i<count ; i++) {
3390 currentLayers[i]->dumpFrameEvents(result);
3391 }
3392}
3393
Dan Stozae77c7662016-05-13 11:37:28 -07003394void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3395 result.append("Buffering stats:\n");
3396 result.append(" [Layer name] <Active time> <Two buffer> "
3397 "<Double buffered> <Triple buffered>\n");
3398 Mutex::Autolock lock(mBufferingStatsMutex);
3399 typedef std::tuple<std::string, float, float, float> BufferTuple;
3400 std::map<float, BufferTuple, std::greater<float>> sorted;
3401 for (const auto& statsPair : mBufferingStats) {
3402 const char* name = statsPair.first.c_str();
3403 const BufferingStats& stats = statsPair.second;
3404 if (stats.numSegments == 0) {
3405 continue;
3406 }
3407 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3408 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3409 stats.totalTime;
3410 float doubleBufferRatio = static_cast<float>(
3411 stats.doubleBufferedTime) / stats.totalTime;
3412 float tripleBufferRatio = static_cast<float>(
3413 stats.tripleBufferedTime) / stats.totalTime;
3414 sorted.insert({activeTime, {name, twoBufferRatio,
3415 doubleBufferRatio, tripleBufferRatio}});
3416 }
3417 for (const auto& sortedPair : sorted) {
3418 float activeTime = sortedPair.first;
3419 const BufferTuple& values = sortedPair.second;
3420 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3421 std::get<0>(values).c_str(), activeTime,
3422 std::get<1>(values), std::get<2>(values),
3423 std::get<3>(values));
3424 }
3425 result.append("\n");
3426}
3427
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003428void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3429 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3430
3431 // TODO: print out if wide-color mode is active or not
3432
3433 for (size_t d = 0; d < mDisplays.size(); d++) {
3434 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3435 int32_t hwcId = displayDevice->getHwcDisplayId();
3436 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3437 continue;
3438 }
3439
3440 result.appendFormat("Display %d color modes:\n", hwcId);
3441 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3442 for (auto&& mode : modes) {
3443 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3444 }
3445
3446 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3447 result.appendFormat(" Current color mode: %s (%d)\n",
3448 decodeColorMode(currentMode).c_str(), currentMode);
3449 }
3450 result.append("\n");
3451}
3452
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3454 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003455{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003456 bool colorize = false;
3457 if (index < args.size()
3458 && (args[index] == String16("--color"))) {
3459 colorize = true;
3460 index++;
3461 }
3462
3463 Colorizer colorizer(colorize);
3464
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465 // figure out if we're stuck somewhere
3466 const nsecs_t now = systemTime();
3467 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3468 const nsecs_t inTransaction(mDebugInTransaction);
3469 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3470 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3471
3472 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003473 * Dump library configuration.
3474 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003475
3476 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003477 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003478 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003479 appendSfConfigString(result);
3480 appendUiConfigString(result);
3481 appendGuiConfigString(result);
3482 result.append("\n");
3483
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003484 result.append("\nWide-Color information:\n");
3485 dumpWideColorInfo(result);
3486
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003487 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003488 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003489 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003490 result.append(SyncFeatures::getInstance().toString());
3491 result.append("\n");
3492
Dan Stoza9e56aa02015-11-02 13:00:03 -08003493 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3494
Andy McFadden41d67d72014-04-25 16:58:34 -07003495 colorizer.bold(result);
3496 result.append("DispSync configuration: ");
3497 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003498 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003499 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003500 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003501 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003502 result.append("\n");
3503
Dan Stozab90cf072015-03-05 11:05:59 -08003504 // Dump static screen stats
3505 result.append("\n");
3506 dumpStaticScreenStats(result);
3507 result.append("\n");
3508
Dan Stozae77c7662016-05-13 11:37:28 -07003509 dumpBufferingStats(result);
3510
Andy McFadden4803b742012-09-24 19:07:20 -07003511 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003512 * Dump the visible layer list
3513 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003514 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003515 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003516 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003517 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003518 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003519 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003520
3521 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003522 * Dump Display state
3523 */
3524
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003525 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003526 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003527 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003528 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3529 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003530 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003531 }
3532
3533 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003534 * Dump SurfaceFlinger global state
3535 */
3536
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003537 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003538 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003539 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003540
Mathias Agopian888c8222012-08-04 21:10:38 -07003541 HWComposer& hwc(getHwComposer());
Polina Bondarenko80c02322017-04-10 10:15:42 +00003542 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003543
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003544 colorizer.bold(result);
3545 result.appendFormat("EGL implementation : %s\n",
3546 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3547 colorizer.reset(result);
3548 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003549 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003550
Mathias Agopian875d8e12013-06-07 15:35:48 -07003551 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003552
Mathias Agopian42977342012-08-05 00:40:46 -07003553 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003554 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3555 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003556 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003557 " last eglSwapBuffers() time: %f us\n"
3558 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003559 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003560 " refresh-rate : %f fps\n"
3561 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003562 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003563 " gpu_to_cpu_unsupported : %d\n"
3564 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003565 mLastSwapBufferTime/1000.0,
3566 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003567 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003568 1e9 / activeConfig->getVsyncPeriod(),
3569 activeConfig->getDpiX(),
3570 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003571 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003572
Mathias Agopian74d211a2013-04-22 16:55:35 +02003573 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003574 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003575
Mathias Agopian74d211a2013-04-22 16:55:35 +02003576 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003577 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003578
3579 /*
3580 * VSYNC state
3581 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003582 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003583 result.append("\n");
3584
3585 /*
3586 * HWC layer minidump
3587 */
3588 for (size_t d = 0; d < mDisplays.size(); d++) {
3589 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3590 int32_t hwcId = displayDevice->getHwcDisplayId();
3591 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3592 continue;
3593 }
3594
3595 result.appendFormat("Display %d HWC layers:\n", hwcId);
3596 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003597 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003598 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003599 });
Dan Stozae22aec72016-08-01 13:20:59 -07003600 result.append("\n");
3601 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003602
3603 /*
3604 * Dump HWComposer state
3605 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003606 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003607 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003608 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003609 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003610 result.appendFormat(" h/w composer %s\n",
3611 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003612 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003613
3614 /*
3615 * Dump gralloc state
3616 */
3617 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3618 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003619}
3620
Mathias Agopian13127d82013-03-05 17:47:11 -08003621const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003622SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003623 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003624 wp<IBinder> dpy;
3625 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3626 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3627 dpy = mDisplays.keyAt(i);
3628 break;
3629 }
3630 }
3631 if (dpy == NULL) {
3632 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3633 // Just use the primary display so we have something to return
3634 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3635 }
3636 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003637}
3638
Keun young Park63f165f2012-08-31 10:53:36 -07003639bool SurfaceFlinger::startDdmConnection()
3640{
3641 void* libddmconnection_dso =
3642 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3643 if (!libddmconnection_dso) {
3644 return false;
3645 }
3646 void (*DdmConnection_start)(const char* name);
3647 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003648 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003649 if (!DdmConnection_start) {
3650 dlclose(libddmconnection_dso);
3651 return false;
3652 }
3653 (*DdmConnection_start)(getServiceName());
3654 return true;
3655}
3656
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003657status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003658 switch (code) {
3659 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003660 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003661 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003662 case CLEAR_ANIMATION_FRAME_STATS:
3663 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003664 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003665 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666 {
3667 // codes that require permission check
3668 IPCThreadState* ipc = IPCThreadState::self();
3669 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003670 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003671 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003672 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003673 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003674 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003675 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003676 break;
3677 }
Robert Carr1db73f62016-12-21 12:58:51 -08003678 /*
3679 * Calling setTransactionState is safe, because you need to have been
3680 * granted a reference to Client* and Handle* to do anything with it.
3681 *
3682 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3683 */
3684 case SET_TRANSACTION_STATE:
3685 case CREATE_SCOPED_CONNECTION:
3686 {
3687 return OK;
3688 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003689 case CAPTURE_SCREEN:
3690 {
3691 // codes that require permission check
3692 IPCThreadState* ipc = IPCThreadState::self();
3693 const int pid = ipc->getCallingPid();
3694 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003695 if ((uid != AID_GRAPHICS) &&
3696 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003697 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003698 return PERMISSION_DENIED;
3699 }
3700 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003701 }
3702 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003703 return OK;
3704}
3705
3706status_t SurfaceFlinger::onTransact(
3707 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3708{
3709 status_t credentialCheck = CheckTransactCodeCredentials(code);
3710 if (credentialCheck != OK) {
3711 return credentialCheck;
3712 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3715 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003716 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003717 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003718 IPCThreadState* ipc = IPCThreadState::self();
3719 const int pid = ipc->getCallingPid();
3720 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003721 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003722 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 return PERMISSION_DENIED;
3724 }
3725 int n;
3726 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003727 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003728 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 return NO_ERROR;
3730 case 1002: // SHOW_UPDATES
3731 n = data.readInt32();
3732 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003733 invalidateHwcGeometry();
3734 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003735 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003737 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003738 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003740 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003741 setTransactionFlags(
3742 eTransactionNeeded|
3743 eDisplayTransactionNeeded|
3744 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003745 return NO_ERROR;
3746 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003747 case 1006:{ // send empty update
3748 signalRefresh();
3749 return NO_ERROR;
3750 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003751 case 1008: // toggle use of hw composer
3752 n = data.readInt32();
3753 mDebugDisableHWC = n ? 1 : 0;
3754 invalidateHwcGeometry();
3755 repaintEverything();
3756 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003757 case 1009: // toggle use of transform hint
3758 n = data.readInt32();
3759 mDebugDisableTransformHint = n ? 1 : 0;
3760 invalidateHwcGeometry();
3761 repaintEverything();
3762 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003763 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003764 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003765 reply->writeInt32(0);
3766 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003767 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003768 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 return NO_ERROR;
3770 case 1013: {
3771 Mutex::Autolock _l(mStateLock);
Polina Bondarenko80c02322017-04-10 10:15:42 +00003772 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003773 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003774 return NO_ERROR;
3775 }
3776 case 1014: {
3777 // daltonize
3778 n = data.readInt32();
3779 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003780 case 1:
3781 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3782 break;
3783 case 2:
3784 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3785 break;
3786 case 3:
3787 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3788 break;
3789 default:
3790 mDaltonizer.setType(ColorBlindnessType::None);
3791 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003792 }
3793 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003794 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003795 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003796 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003797 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003798 invalidateHwcGeometry();
3799 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003800 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003802 case 1015: {
3803 // apply a color matrix
3804 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003805 if (n) {
3806 // color matrix is sent as mat3 matrix followed by vec3
3807 // offset, then packed into a mat4 where the last row is
3808 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003809 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003810 for (size_t j = 0; j < 4; j++) {
3811 mColorMatrix[i][j] = data.readFloat();
3812 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003813 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003814 } else {
3815 mColorMatrix = mat4();
3816 }
3817 invalidateHwcGeometry();
3818 repaintEverything();
3819 return NO_ERROR;
3820 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003821 // This is an experimental interface
3822 // Needs to be shifted to proper binder interface when we productize
3823 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003824 n = data.readInt32();
3825 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003826 return NO_ERROR;
3827 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003828 case 1017: {
3829 n = data.readInt32();
3830 mForceFullDamage = static_cast<bool>(n);
3831 return NO_ERROR;
3832 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003833 case 1018: { // Modify Choreographer's phase offset
3834 n = data.readInt32();
3835 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3836 return NO_ERROR;
3837 }
3838 case 1019: { // Modify SurfaceFlinger's phase offset
3839 n = data.readInt32();
3840 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3841 return NO_ERROR;
3842 }
Irvel468051e2016-06-13 16:44:44 -07003843 case 1020: { // Layer updates interceptor
3844 n = data.readInt32();
3845 if (n) {
3846 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003847 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003848 }
3849 else{
3850 ALOGV("Interceptor disabled");
3851 mInterceptor.disable();
3852 }
3853 return NO_ERROR;
3854 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003855 case 1021: { // Disable HWC virtual displays
3856 n = data.readInt32();
3857 mUseHwcVirtualDisplays = !n;
3858 return NO_ERROR;
3859 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860 }
3861 }
3862 return err;
3863}
3864
Mathias Agopian53331da2011-08-22 21:44:41 -07003865void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003866 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003867 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003868}
3869
Mathias Agopian59119e62010-10-11 12:37:43 -07003870// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003871// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003872// ---------------------------------------------------------------------------
3873
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003874/* The code below is here to handle b/8734824
3875 *
3876 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003877 * from the surfaceflinger thread to the calling binder thread, where they
3878 * are executed. This allows the calling thread in the calling process to be
3879 * reused and not depend on having "enough" binder threads to handle the
3880 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003881 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003882class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003883 /* Parts of GraphicProducerWrapper are run on two different threads,
3884 * communicating by sending messages via Looper but also by shared member
3885 * data. Coherence maintenance is subtle and in places implicit (ugh).
3886 *
3887 * Don't rely on Looper's sendMessage/handleMessage providing
3888 * release/acquire semantics for any data not actually in the Message.
3889 * Data going from surfaceflinger to binder threads needs to be
3890 * synchronized explicitly.
3891 *
3892 * Barrier open/wait do provide release/acquire semantics. This provides
3893 * implicit synchronization for data coming back from binder to
3894 * surfaceflinger threads.
3895 */
3896
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003897 sp<IGraphicBufferProducer> impl;
3898 sp<Looper> looper;
3899 status_t result;
3900 bool exitPending;
3901 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003902 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003903 uint32_t code;
3904 Parcel const* data;
3905 Parcel* reply;
3906
3907 enum {
3908 MSG_API_CALL,
3909 MSG_EXIT
3910 };
3911
3912 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003913 * Called on surfaceflinger thread. This is called by our "fake"
3914 * BpGraphicBufferProducer. We package the data and reply Parcel and
3915 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003916 */
3917 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003918 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003919 this->code = code;
3920 this->data = &data;
3921 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003922 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003923 // if we've exited, we run the message synchronously right here.
3924 // note (JH): as far as I can tell from looking at the code, this
3925 // never actually happens. if it does, i'm not sure if it happens
3926 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 handleMessage(Message(MSG_API_CALL));
3928 } else {
3929 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003930 // Prevent stores to this->{code, data, reply} from being
3931 // reordered later than the construction of Message.
3932 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003933 looper->sendMessage(this, Message(MSG_API_CALL));
3934 barrier.wait();
3935 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003936 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003937 }
3938
3939 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003940 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003941 * call the real BpGraphicBufferProducer.
3942 */
3943 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003944 int what = message.what;
3945 // Prevent reads below from happening before the read from Message
3946 atomic_thread_fence(memory_order_acquire);
3947 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003948 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003949 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003950 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003951 exitRequested = true;
3952 }
3953 }
3954
3955public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003956 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003957 : impl(impl),
3958 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003959 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003960 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003961 exitRequested(false),
3962 code(0),
3963 data(NULL),
3964 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003965 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003966
Jesse Hallb154c422014-07-13 12:47:02 -07003967 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003968 status_t waitForResponse() {
3969 do {
3970 looper->pollOnce(-1);
3971 } while (!exitRequested);
3972 return result;
3973 }
3974
Jesse Hallb154c422014-07-13 12:47:02 -07003975 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003976 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003977 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003978 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003979 // Ensure this->result is visible to the binder thread before it
3980 // handles the message.
3981 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003982 looper->sendMessage(this, Message(MSG_EXIT));
3983 }
3984};
3985
3986
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003987status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3988 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003989 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003990 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003991 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003992
3993 if (CC_UNLIKELY(display == 0))
3994 return BAD_VALUE;
3995
3996 if (CC_UNLIKELY(producer == 0))
3997 return BAD_VALUE;
3998
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003999 // if we have secure windows on this display, never allow the screen capture
4000 // unless the producer interface is local (i.e.: we can take a screenshot for
4001 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004002 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004003
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004004 // Convert to surfaceflinger's internal rotation type.
4005 Transform::orientation_flags rotationFlags;
4006 switch (rotation) {
4007 case ISurfaceComposer::eRotateNone:
4008 rotationFlags = Transform::ROT_0;
4009 break;
4010 case ISurfaceComposer::eRotate90:
4011 rotationFlags = Transform::ROT_90;
4012 break;
4013 case ISurfaceComposer::eRotate180:
4014 rotationFlags = Transform::ROT_180;
4015 break;
4016 case ISurfaceComposer::eRotate270:
4017 rotationFlags = Transform::ROT_270;
4018 break;
4019 default:
4020 rotationFlags = Transform::ROT_0;
4021 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4022 break;
4023 }
4024
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004025 class MessageCaptureScreen : public MessageBase {
4026 SurfaceFlinger* flinger;
4027 sp<IBinder> display;
4028 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004029 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004030 uint32_t reqWidth, reqHeight;
4031 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004032 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004033 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004034 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004035 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004036 public:
4037 MessageCaptureScreen(SurfaceFlinger* flinger,
4038 const sp<IBinder>& display,
4039 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004040 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004041 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004042 bool useIdentityTransform,
4043 Transform::orientation_flags rotation,
4044 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004045 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004046 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004047 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004048 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004049 rotation(rotation), result(PERMISSION_DENIED),
4050 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004051 {
4052 }
4053 status_t getResult() const {
4054 return result;
4055 }
4056 virtual bool handler() {
4057 Mutex::Autolock _l(flinger->mStateLock);
4058 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08004059 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004060 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004061 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004062 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004063 return true;
4064 }
4065 };
4066
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004067 // this creates a "fake" BBinder which will serve as a "fake" remote
4068 // binder to receive the marshaled calls and forward them to the
4069 // real remote (a BpGraphicBufferProducer)
4070 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4071
4072 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4073 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004074 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004075 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004076 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004077 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004078
4079 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004080 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004081 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004082 }
4083 return res;
4084}
4085
Mathias Agopian180f10d2013-04-10 22:55:41 -07004086
4087void SurfaceFlinger::renderScreenImplLocked(
4088 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004089 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004090 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004091 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004092{
4093 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004094 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004095
4096 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004097 const int32_t hw_w = hw->getWidth();
4098 const int32_t hw_h = hw->getHeight();
4099 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004100 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004101
Dan Stozac1879002014-05-22 15:59:05 -07004102 // if a default or invalid sourceCrop is passed in, set reasonable values
4103 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4104 !sourceCrop.isValid()) {
4105 sourceCrop.setLeftTop(Point(0, 0));
4106 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4107 }
4108
4109 // ensure that sourceCrop is inside screen
4110 if (sourceCrop.left < 0) {
4111 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4112 }
Dan Stozabe31f442014-06-11 11:20:54 -07004113 if (sourceCrop.right > hw_w) {
4114 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004115 }
4116 if (sourceCrop.top < 0) {
4117 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4118 }
Dan Stozabe31f442014-06-11 11:20:54 -07004119 if (sourceCrop.bottom > hw_h) {
4120 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004121 }
4122
Mathias Agopian180f10d2013-04-10 22:55:41 -07004123 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004124 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004125
4126 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004127 engine.setViewportAndProjection(
4128 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004129 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004130
4131 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004132 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004133
Robert Carr1f0a16a2016-10-24 16:27:39 -07004134 // We loop through the first level of layers without traversing,
4135 // as we need to interpret min/max layer Z in the top level Z space.
4136 for (const auto& layer : mDrawingState.layersSortedByZ) {
4137 if (layer->getLayerStack() != hw->getLayerStack()) {
4138 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004139 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004140 const Layer::State& state(layer->getDrawingState());
4141 if (state.z < minLayerZ || state.z > maxLayerZ) {
4142 continue;
4143 }
4144 layer->traverseInZOrder([&](Layer* layer) {
4145 if (!layer->isVisible()) {
4146 return;
4147 }
4148 if (filtering) layer->setFiltering(true);
4149 layer->draw(hw, useIdentityTransform);
4150 if (filtering) layer->setFiltering(false);
4151 });
4152 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004153
Mathias Agopian931bda12013-08-28 18:11:46 -07004154 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004155}
4156
4157
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004158status_t SurfaceFlinger::captureScreenImplLocked(
4159 const sp<const DisplayDevice>& hw,
4160 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004161 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004162 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004163 bool useIdentityTransform, Transform::orientation_flags rotation,
4164 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004165{
4166 ATRACE_CALL();
4167
Mathias Agopian180f10d2013-04-10 22:55:41 -07004168 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004169 uint32_t hw_w = hw->getWidth();
4170 uint32_t hw_h = hw->getHeight();
4171
4172 if (rotation & Transform::ROT_90) {
4173 std::swap(hw_w, hw_h);
4174 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004175
Mathias Agopian180f10d2013-04-10 22:55:41 -07004176 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4177 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4178 reqWidth, reqHeight, hw_w, hw_h);
4179 return BAD_VALUE;
4180 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004181
Mathias Agopian180f10d2013-04-10 22:55:41 -07004182 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4183 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4184
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004185 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004186 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004187 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004188 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4189 (state.z < minLayerZ || state.z > maxLayerZ)) {
4190 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004191 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004192 layer->traverseInZOrder([&](Layer *layer) {
4193 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4194 layer->isSecure());
4195 });
4196 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004197
4198 if (!isLocalScreenshot && secureLayerIsVisible) {
4199 ALOGW("FB is protected: PERMISSION_DENIED");
4200 return PERMISSION_DENIED;
4201 }
4202
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004203 // create a surface (because we're a producer, and we need to
4204 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004205 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004206
4207 // Put the screenshot Surface into async mode so that
4208 // Layer::headFenceHasSignaled will always return true and we'll latch the
4209 // first buffer regardless of whether or not its acquire fence has
4210 // signaled. This is needed to avoid a race condition in the rotation
4211 // animation. See b/30209608
4212 sur->setAsyncMode(true);
4213
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004214 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004215
Michael Lentine5a16a622015-05-21 13:48:24 -07004216 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4217 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004218 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4219 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004220
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004221 int err = 0;
4222 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004223 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004224 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4225 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004226
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004227 if (err == NO_ERROR) {
4228 ANativeWindowBuffer* buffer;
4229 /* TODO: Once we have the sync framework everywhere this can use
4230 * server-side waits on the fence that dequeueBuffer returns.
4231 */
4232 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4233 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004234 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004235 // create an EGLImage from the buffer so we can later
4236 // turn it into a texture
4237 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4238 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4239 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004240 // this binds the given EGLImage as a framebuffer for the
4241 // duration of this scope.
4242 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4243 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004244 // this will in fact render into our dequeued buffer
4245 // via an FBO, which means we didn't have to create
4246 // an EGLSurface and therefore we're not
4247 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004248 renderScreenImplLocked(
4249 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4250 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004251
Riley Andrews86639902014-08-15 12:27:24 -07004252 // Attempt to create a sync khr object that can produce a sync point. If that
4253 // isn't available, create a non-dupable sync object in the fallback path and
4254 // wait on it directly.
4255 EGLSyncKHR sync;
4256 if (!DEBUG_SCREENSHOTS) {
4257 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004258 // native fence fd will not be populated until flush() is done.
4259 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004260 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004261 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004262 }
Riley Andrews86639902014-08-15 12:27:24 -07004263 if (sync != EGL_NO_SYNC_KHR) {
4264 // get the sync fd
4265 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4266 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4267 ALOGW("captureScreen: failed to dup sync khr object");
4268 syncFd = -1;
4269 }
4270 eglDestroySyncKHR(mEGLDisplay, sync);
4271 } else {
4272 // fallback path
4273 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4274 if (sync != EGL_NO_SYNC_KHR) {
4275 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4276 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4277 EGLint eglErr = eglGetError();
4278 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4279 ALOGW("captureScreen: fence wait timed out");
4280 } else {
4281 ALOGW_IF(eglErr != EGL_SUCCESS,
4282 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4283 }
4284 eglDestroySyncKHR(mEGLDisplay, sync);
4285 } else {
4286 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4287 }
4288 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004289 if (DEBUG_SCREENSHOTS) {
4290 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4291 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4292 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4293 hw, minLayerZ, maxLayerZ);
4294 delete [] pixels;
4295 }
4296
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004297 } else {
4298 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4299 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004300 window->cancelBuffer(window, buffer, syncFd);
4301 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004302 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004303 // destroy our image
4304 eglDestroyImageKHR(mEGLDisplay, image);
4305 } else {
4306 result = BAD_VALUE;
4307 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004308 if (buffer) {
4309 // queueBuffer takes ownership of syncFd
4310 result = window->queueBuffer(window, buffer, syncFd);
4311 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004312 }
4313 } else {
4314 result = BAD_VALUE;
4315 }
4316 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4317 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004318
Mathias Agopian74c40c02010-09-29 13:02:36 -07004319 return result;
4320}
4321
Mathias Agopiand5556842013-09-19 17:08:37 -07004322void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004323 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004324 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004325 for (size_t y=0 ; y<h ; y++) {
4326 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4327 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004328 if (p[x] != 0xFF000000) return;
4329 }
4330 }
4331 ALOGE("*** we just took a black screenshot ***\n"
4332 "requested minz=%d, maxz=%d, layerStack=%d",
4333 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004334
Robert Carr2047fae2016-11-28 14:09:09 -08004335 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004336 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004337 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004338 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4339 state.z <= maxLayerZ) {
4340 layer->traverseInZOrder([&](Layer* layer) {
4341 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4342 layer->isVisible() ? '+' : '-',
4343 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004344 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004345 i++;
4346 });
4347 }
4348 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004349 }
4350}
4351
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004352// ---------------------------------------------------------------------------
4353
Robert Carr2047fae2016-11-28 14:09:09 -08004354void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4355 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004356}
4357
Robert Carr2047fae2016-11-28 14:09:09 -08004358void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4359 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004360}
4361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004363
4364
4365#if defined(__gl_h_)
4366#error "don't include gl/gl.h in this file"
4367#endif
4368
4369#if defined(__gl2_h_)
4370#error "don't include gl2/gl2.h in this file"
4371#endif