blob: c72f8e0db6458de103223011bb9bc72c4991c781 [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
Ian Elliott5c34de22017-04-10 14:42:30 -0600581 // Inform native graphics APIs whether the present timestamp is supported:
582 if (getHwComposer().hasCapability(
583 HWC2::Capability::PresentFenceIsNotReliable)) {
584 property_set(kTimestampProperty, "0");
585 } else {
586 property_set(kTimestampProperty, "1");
587 }
588
Steven Thomas050b2c82017-03-06 11:45:16 -0800589 if (useVrFlinger) {
590 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
591 mVrFlingerRequestsDisplay = requestDisplay;
592 signalTransaction();
593 };
594 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
595 vrFlingerRequestDisplayCallback);
596 if (!mVrFlinger) {
597 ALOGE("Failed to start vrflinger");
598 }
599 }
600
Mathias Agopian875d8e12013-06-07 15:35:48 -0700601 // retrieve the EGL context that was selected/created
602 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700603
Mathias Agopianda27af92012-09-13 18:17:13 -0700604 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
605 "couldn't create EGLContext");
606
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607 // make the GLContext current so that we can create textures when creating
608 // Layers (which may happens before we render something)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000609 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700610
Jamie Gennisd1700752013-10-14 12:22:52 -0700611 mEventControlThread = new EventControlThread(this);
612 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
613
Mathias Agopian92a979a2012-08-02 18:32:23 -0700614 // initialize our drawing state
615 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700616
Andy McFadden13a082e2012-08-24 10:16:42 -0700617 // set initial conditions (e.g. unblank default device)
618 initializeDisplays();
619
Dan Stoza4e637772016-07-28 13:31:51 -0700620 mRenderEngine->primeCache();
621
Wei Wangb254fa32017-01-31 17:43:23 -0800622 mStartBootAnimThread = new StartBootAnimThread();
623 if (mStartBootAnimThread->Start() != NO_ERROR) {
624 ALOGE("Run StartBootAnimThread failed!");
625 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700628}
629
Mathias Agopiana67e4182012-06-19 17:26:12 -0700630void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800631 // Start boot animation service by setting a property mailbox
632 // if property setting thread is already running, Start() will be just a NOP
633 mStartBootAnimThread->Start();
634 // Wait until property was set
635 if (mStartBootAnimThread->join() != NO_ERROR) {
636 ALOGE("Join StartBootAnimThread failed!");
637 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700638}
639
Mathias Agopian875d8e12013-06-07 15:35:48 -0700640size_t SurfaceFlinger::getMaxTextureSize() const {
641 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700642}
643
Mathias Agopian875d8e12013-06-07 15:35:48 -0700644size_t SurfaceFlinger::getMaxViewportDims() const {
645 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700646}
647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800649
Jamie Gennis582270d2011-08-17 18:19:00 -0700650bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800651 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800652 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800653 return authenticateSurfaceTextureLocked(bufferProducer);
654}
655
656bool SurfaceFlinger::authenticateSurfaceTextureLocked(
657 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800658 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700659 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800660}
661
Brian Anderson6b376712017-04-04 10:51:39 -0700662status_t SurfaceFlinger::getSupportedFrameTimestamps(
663 std::vector<FrameEvent>* outSupported) const {
664 *outSupported = {
665 FrameEvent::REQUESTED_PRESENT,
666 FrameEvent::ACQUIRE,
667 FrameEvent::LATCH,
668 FrameEvent::FIRST_REFRESH_START,
669 FrameEvent::LAST_REFRESH_START,
670 FrameEvent::GPU_COMPOSITION_DONE,
671 FrameEvent::DEQUEUE_READY,
672 FrameEvent::RELEASE,
673 };
674 if (!getHwComposer().hasCapability(
675 HWC2::Capability::PresentFenceIsNotReliable)) {
676 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
677 }
678 return NO_ERROR;
679}
680
Dan Stoza7f7da322014-05-02 15:26:25 -0700681status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
682 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700683 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700684 return BAD_VALUE;
685 }
686
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500687 if (!display.get())
688 return NAME_NOT_FOUND;
689
Jesse Hall692c7232012-11-08 15:41:56 -0800690 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700691 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800692 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700693 type = i;
694 break;
695 }
696 }
697
698 if (type < 0) {
699 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700700 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700701
Mathias Agopian8b736f12012-08-13 17:54:26 -0700702 // TODO: Not sure if display density should handled by SF any longer
703 class Density {
704 static int getDensityFromProperty(char const* propName) {
705 char property[PROPERTY_VALUE_MAX];
706 int density = 0;
707 if (property_get(propName, property, NULL) > 0) {
708 density = atoi(property);
709 }
710 return density;
711 }
712 public:
713 static int getEmuDensity() {
714 return getDensityFromProperty("qemu.sf.lcd_density"); }
715 static int getBuildDensity() {
716 return getDensityFromProperty("ro.sf.lcd_density"); }
717 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700718
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700722 DisplayInfo info = DisplayInfo();
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 float xdpi = hwConfig->getDpiX();
725 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700726
727 if (type == DisplayDevice::DISPLAY_PRIMARY) {
728 // The density of the device is provided by a build property
729 float density = Density::getBuildDensity() / 160.0f;
730 if (density == 0) {
731 // the build doesn't provide a density -- this is wrong!
732 // use xdpi instead
733 ALOGE("ro.sf.lcd_density must be defined as a build property");
734 density = xdpi / 160.0f;
735 }
736 if (Density::getEmuDensity()) {
737 // if "qemu.sf.lcd_density" is specified, it overrides everything
738 xdpi = ydpi = density = Density::getEmuDensity();
739 density /= 160.0f;
740 }
741 info.density = density;
742
743 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000744 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
745 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700746 } else {
747 // TODO: where should this value come from?
748 static const int TV_DENSITY = 213;
749 info.density = TV_DENSITY / 160.0f;
750 info.orientation = 0;
751 }
752
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 info.w = hwConfig->getWidth();
754 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700755 info.xdpi = xdpi;
756 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800757 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900758 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759
Andy McFadden91b2ca82014-06-13 14:04:23 -0700760 // This is how far in advance a buffer must be queued for
761 // presentation at a given time. If you want a buffer to appear
762 // on the screen at time N, you must submit the buffer before
763 // (N - presentationDeadline).
764 //
765 // Normally it's one full refresh period (to give SF a chance to
766 // latch the buffer), but this can be reduced by configuring a
767 // DispSync offset. Any additional delays introduced by the hardware
768 // composer or panel must be accounted for here.
769 //
770 // We add an additional 1ms to allow for processing time and
771 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800772 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800773 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700774
775 // All non-virtual displays are currently considered secure.
776 info.secure = true;
777
Michael Wright28f24d02016-07-12 13:30:53 -0700778 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779 }
780
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 return NO_ERROR;
782}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700783
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800784status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700785 DisplayStatInfo* stats) {
786 if (stats == NULL) {
787 return BAD_VALUE;
788 }
789
790 // FIXME for now we always return stats for the primary display
791 memset(stats, 0, sizeof(*stats));
792 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
793 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
794 return NO_ERROR;
795}
796
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700797int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800798 if (display == NULL) {
799 ALOGE("%s : display is NULL", __func__);
800 return BAD_VALUE;
801 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700802 sp<DisplayDevice> device(getDisplayDevice(display));
803 if (device != NULL) {
804 return device->getActiveConfig();
805 }
806 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700807}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700808
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700809void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
810 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
811 this);
812 int32_t type = hw->getDisplayType();
813 int currentMode = hw->getActiveConfig();
814
815 if (mode == currentMode) {
816 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
817 return;
818 }
819
820 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
821 ALOGW("Trying to set config for virtual display");
822 return;
823 }
824
825 hw->setActiveConfig(mode);
826 getHwComposer().setActiveConfig(type, mode);
827}
828
829status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
830 class MessageSetActiveConfig: public MessageBase {
831 SurfaceFlinger& mFlinger;
832 sp<IBinder> mDisplay;
833 int mMode;
834 public:
835 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
836 int mode) :
837 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
838 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700839 Vector<DisplayInfo> configs;
840 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700841 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700842 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700843 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700844 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700845 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700846 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
847 if (hw == NULL) {
848 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700849 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700850 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
851 ALOGW("Attempt to set active config = %d for virtual display",
852 mMode);
853 } else {
854 mFlinger.setActiveConfigInternal(hw, mMode);
855 }
856 return true;
857 }
858 };
859 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
860 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700861 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700862}
Michael Wright28f24d02016-07-12 13:30:53 -0700863status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
864 Vector<android_color_mode_t>* outColorModes) {
865 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
866 return BAD_VALUE;
867 }
868
869 if (!display.get()) {
870 return NAME_NOT_FOUND;
871 }
872
873 int32_t type = NAME_NOT_FOUND;
874 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
875 if (display == mBuiltinDisplays[i]) {
876 type = i;
877 break;
878 }
879 }
880
881 if (type < 0) {
882 return type;
883 }
884
885 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
886 outColorModes->clear();
887 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
888
889 return NO_ERROR;
890}
891
892android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
893 sp<DisplayDevice> device(getDisplayDevice(display));
894 if (device != nullptr) {
895 return device->getActiveColorMode();
896 }
897 return static_cast<android_color_mode_t>(BAD_VALUE);
898}
899
900void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
901 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700902 int32_t type = hw->getDisplayType();
903 android_color_mode_t currentMode = hw->getActiveColorMode();
904
905 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700906 return;
907 }
908
909 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
910 ALOGW("Trying to set config for virtual display");
911 return;
912 }
913
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600914 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
915 hw->getDisplayType());
916
Michael Wright28f24d02016-07-12 13:30:53 -0700917 hw->setActiveColorMode(mode);
918 getHwComposer().setActiveColorMode(type, mode);
919}
920
921
922status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
923 android_color_mode_t colorMode) {
924 class MessageSetActiveColorMode: public MessageBase {
925 SurfaceFlinger& mFlinger;
926 sp<IBinder> mDisplay;
927 android_color_mode_t mMode;
928 public:
929 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
930 android_color_mode_t mode) :
931 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
932 virtual bool handler() {
933 Vector<android_color_mode_t> modes;
934 mFlinger.getDisplayColorModes(mDisplay, &modes);
935 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
936 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600937 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
938 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700939 return true;
940 }
941 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
942 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600943 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
944 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700945 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600946 ALOGW("Attempt to set active color mode %s %d for virtual display",
947 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700948 } else {
949 mFlinger.setActiveColorModeInternal(hw, mMode);
950 }
951 return true;
952 }
953 };
954 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
955 postMessageSync(msg);
956 return NO_ERROR;
957}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700958
Svetoslavd85084b2014-03-20 10:28:31 -0700959status_t SurfaceFlinger::clearAnimationFrameStats() {
960 Mutex::Autolock _l(mStateLock);
961 mAnimFrameTracker.clearStats();
962 return NO_ERROR;
963}
964
965status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
966 Mutex::Autolock _l(mStateLock);
967 mAnimFrameTracker.getStats(outStats);
968 return NO_ERROR;
969}
970
Dan Stozac4f471e2016-03-24 09:31:08 -0700971status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
972 HdrCapabilities* outCapabilities) const {
973 Mutex::Autolock _l(mStateLock);
974
975 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
976 if (displayDevice == nullptr) {
977 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
978 return BAD_VALUE;
979 }
980
981 std::unique_ptr<HdrCapabilities> capabilities =
982 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
983 if (capabilities) {
984 std::swap(*outCapabilities, *capabilities);
985 } else {
986 return BAD_VALUE;
987 }
988
989 return NO_ERROR;
990}
991
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700992status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
993 if (enable == mInjectVSyncs) {
994 return NO_ERROR;
995 }
996
997 if (enable) {
998 mInjectVSyncs = enable;
999 ALOGV("VSync Injections enabled");
1000 if (mVSyncInjector.get() == nullptr) {
1001 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001002 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001003 }
1004 mEventQueue.setEventThread(mInjectorEventThread);
1005 } else {
1006 mInjectVSyncs = enable;
1007 ALOGV("VSync Injections disabled");
1008 mEventQueue.setEventThread(mSFEventThread);
1009 mVSyncInjector.clear();
1010 }
1011 return NO_ERROR;
1012}
1013
1014status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1015 if (!mInjectVSyncs) {
1016 ALOGE("VSync Injections not enabled");
1017 return BAD_VALUE;
1018 }
1019 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1020 ALOGV("Injecting VSync inside SurfaceFlinger");
1021 mVSyncInjector->onInjectSyncEvent(when);
1022 }
1023 return NO_ERROR;
1024}
1025
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001026// ----------------------------------------------------------------------------
1027
1028sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001029 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001030}
1031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001033
1034void SurfaceFlinger::waitForEvent() {
1035 mEventQueue.waitMessage();
1036}
1037
1038void SurfaceFlinger::signalTransaction() {
1039 mEventQueue.invalidate();
1040}
1041
1042void SurfaceFlinger::signalLayerUpdate() {
1043 mEventQueue.invalidate();
1044}
1045
1046void SurfaceFlinger::signalRefresh() {
1047 mEventQueue.refresh();
1048}
1049
1050status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001051 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001052 return mEventQueue.postMessage(msg, reltime);
1053}
1054
1055status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001056 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001057 status_t res = mEventQueue.postMessage(msg, reltime);
1058 if (res == NO_ERROR) {
1059 msg->wait();
1060 }
1061 return res;
1062}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001063
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001064void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001065 do {
1066 waitForEvent();
1067 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068}
1069
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070void SurfaceFlinger::enableHardwareVsync() {
1071 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001072 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001074 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1075 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001077 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078}
1079
Jesse Hall948fe0c2013-10-14 12:56:09 -07001080void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001081 Mutex::Autolock _l(mHWVsyncLock);
1082
Jesse Hall948fe0c2013-10-14 12:56:09 -07001083 if (makeAvailable) {
1084 mHWVsyncAvailable = true;
1085 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001086 // Hardware vsync is not currently available, so abort the resync
1087 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001088 return;
1089 }
1090
Dan Stoza9e56aa02015-11-02 13:00:03 -08001091 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1092 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093
1094 mPrimaryDispSync.reset();
1095 mPrimaryDispSync.setPeriod(period);
1096
1097 if (!mPrimaryHWVsyncEnabled) {
1098 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001099 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1100 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001101 mPrimaryHWVsyncEnabled = true;
1102 }
1103}
1104
Jesse Hall948fe0c2013-10-14 12:56:09 -07001105void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106 Mutex::Autolock _l(mHWVsyncLock);
1107 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001108 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1109 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110 mPrimaryDispSync.endResync();
1111 mPrimaryHWVsyncEnabled = false;
1112 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001113 if (makeUnavailable) {
1114 mHWVsyncAvailable = false;
1115 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116}
1117
Tim Murray4a4e4a22016-04-19 16:29:23 +00001118void SurfaceFlinger::resyncWithRateLimit() {
1119 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1120 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001121 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001122 }
1123}
1124
Steven Thomas3cfac282017-02-06 12:29:30 -08001125void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1126 nsecs_t timestamp) {
1127 Mutex::Autolock lock(mStateLock);
1128 // Ignore any vsyncs from the non-active hardware composer.
1129 if (composer != mHwc) {
1130 return;
1131 }
1132
Jamie Gennisd1700752013-10-14 12:22:52 -07001133 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001134
Jamie Gennisd1700752013-10-14 12:22:52 -07001135 { // Scope for the lock
1136 Mutex::Autolock _l(mHWVsyncLock);
1137 if (type == 0 && mPrimaryHWVsyncEnabled) {
1138 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001139 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001140 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001141
1142 if (needsHwVsync) {
1143 enableHardwareVsync();
1144 } else {
1145 disableHardwareVsync(false);
1146 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001147}
1148
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001149void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001150 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001151 *compositorTiming = mCompositorTiming;
1152}
1153
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001154void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001155 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1156 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1157 Mutex::Autolock lock(mStateLock);
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001158
1159 // All non-virtual displays are currently considered secure.
1160 bool isSecure = true;
1161
1162 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1163
1164 // When we're using the vr composer, the assumption is that we've
1165 // already created the IBinder object for the primary display.
1166 if (!mHwc->isUsingVrComposer()) {
1167 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1168 }
1169
1170 wp<IBinder> token = mBuiltinDisplays[type];
1171
1172 sp<IGraphicBufferProducer> producer;
1173 sp<IGraphicBufferConsumer> consumer;
1174 BufferQueue::createBufferQueue(&producer, &consumer,
1175 new GraphicBufferAlloc());
1176
1177 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1178 DisplayDevice::DISPLAY_PRIMARY, consumer);
1179
1180 bool hasWideColorModes = false;
1181 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1182 for (android_color_mode_t colorMode : modes) {
1183 switch (colorMode) {
1184 case HAL_COLOR_MODE_DISPLAY_P3:
1185 case HAL_COLOR_MODE_ADOBE_RGB:
1186 case HAL_COLOR_MODE_DCI_P3:
1187 hasWideColorModes = true;
1188 break;
1189 default:
1190 break;
1191 }
1192 }
1193 sp<DisplayDevice> hw =
1194 new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1195 producer, mRenderEngine->getEGLConfig(),
1196 hasWideColorModes && hasWideColorDisplay);
1197 mDisplays.add(token, hw);
1198 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1199 if (hasWideColorModes && hasWideColorDisplay) {
1200 defaultColorMode = HAL_COLOR_MODE_SRGB;
1201 }
1202 setActiveColorModeInternal(hw, defaultColorMode);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 } else {
1204 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001205 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001206 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001208 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001209 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1210 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001211 }
1212 setTransactionFlags(eDisplayTransactionNeeded);
1213
Andy McFadden9e9689c2012-10-10 18:17:51 -07001214 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001215 }
Mathias Agopian86303202012-07-24 22:46:10 -07001216}
1217
Steven Thomas3cfac282017-02-06 12:29:30 -08001218void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1219 Mutex::Autolock lock(mStateLock);
1220 if (composer == mHwc) {
1221 repaintEverything();
1222 } else {
1223 // This isn't from our current hardware composer. If it's a callback
1224 // from the real composer, forward the refresh request to vr
1225 // flinger. Otherwise ignore it.
1226 if (!composer->isUsingVrComposer()) {
1227 mVrFlinger->OnHardwareComposerRefresh();
1228 }
1229 }
1230}
1231
Dan Stoza9e56aa02015-11-02 13:00:03 -08001232void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001233 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001234 getHwComposer().setVsyncEnabled(disp,
1235 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001236}
1237
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001238void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1239 for (size_t i = 0; i < layers.size(); ++i) {
1240 layers[i]->clearHwcLayers();
1241 }
1242}
1243
1244void SurfaceFlinger::resetHwc() {
1245 disableHardwareVsync(true);
1246 clearHwcLayers(mDrawingState.layersSortedByZ);
1247 clearHwcLayers(mCurrentState.layersSortedByZ);
1248 // Clear the drawing state so that the logic inside of
1249 // handleTransactionLocked will fire. It will determine the delta between
1250 // mCurrentState and mDrawingState and re-apply all changes when we make the
1251 // transition.
1252 mDrawingState.displays.clear();
1253 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001254 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001255}
1256
Steven Thomas050b2c82017-03-06 11:45:16 -08001257void SurfaceFlinger::updateVrFlinger() {
1258 if (!mVrFlinger)
1259 return;
1260 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1261 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001262 return;
1263 }
Steven Thomas050b2c82017-03-06 11:45:16 -08001264 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001265 // Construct new HWComposer without holding any locks.
1266 mVrHwc = new HWComposer(true);
1267 ALOGV("Vr HWC created");
1268 }
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001269 {
1270 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001271
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001272 if (vrFlingerRequestsDisplay) {
1273 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001274
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001275 mHwc = mVrHwc;
1276 mVrFlinger->GrantDisplayOwnership();
1277 } else {
1278 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001279
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001280 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001281
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001282 mHwc = mRealHwc;
1283 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001284 }
1285
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001286 mVisibleRegionsDirty = true;
1287 invalidateHwcGeometry();
1288 android_atomic_or(1, &mRepaintEverything);
1289 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001290 }
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001291 if (mVrHwc) {
1292 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1293 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294}
1295
Mathias Agopian4fec8732012-06-29 14:12:52 -07001296void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001297 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001298 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001299 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001300 bool frameMissed = !mHadClientComposition &&
1301 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001302 (mPreviousPresentFence->getSignalTime() ==
1303 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001304 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001305 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001306 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001307 signalLayerUpdate();
1308 break;
1309 }
1310
Steven Thomas050b2c82017-03-06 11:45:16 -08001311 // Now that we're going to make it to the handleMessageTransaction()
1312 // call below it's safe to call updateVrFlinger(), which will
1313 // potentially trigger a display handoff.
1314 updateVrFlinger();
1315
Dan Stoza6b9454d2014-11-07 16:00:59 -08001316 bool refreshNeeded = handleMessageTransaction();
1317 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001318 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001319 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001320 // Signal a refresh if a transaction modified the window state,
1321 // a new buffer was latched, or if HWC has requested a full
1322 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001323 signalRefresh();
1324 }
1325 break;
1326 }
1327 case MessageQueue::REFRESH: {
1328 handleMessageRefresh();
1329 break;
1330 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001331 }
1332}
1333
Dan Stoza6b9454d2014-11-07 16:00:59 -08001334bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001335 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001336 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001337 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001338 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001339 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001340 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001341}
1342
Dan Stoza6b9454d2014-11-07 16:00:59 -08001343bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001345 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001346}
1347
1348void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001349 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001350
Pablo Ceballos40845df2016-01-25 17:41:15 -08001351 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001352
Brian Andersond6927fb2016-07-23 23:37:30 -07001353 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001354 rebuildLayerStacks();
1355 setUpHWComposer();
1356 doDebugFlashRegions();
1357 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001358 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001359
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001360 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001361
1362 mHadClientComposition = false;
1363 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1364 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1365 mHadClientComposition = mHadClientComposition ||
1366 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1367 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001368
Dan Stoza9e56aa02015-11-02 13:00:03 -08001369 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001370}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001371
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372void SurfaceFlinger::doDebugFlashRegions()
1373{
1374 // is debugging enabled
1375 if (CC_LIKELY(!mDebugRegion))
1376 return;
1377
1378 const bool repaintEverything = mRepaintEverything;
1379 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1380 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001381 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001382 // transform the dirty region into this screen's coordinate space
1383 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1384 if (!dirtyRegion.isEmpty()) {
1385 // redraw the whole screen
1386 doComposeSurfaces(hw, Region(hw->bounds()));
1387
1388 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001389 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001390 RenderEngine& engine(getRenderEngine());
1391 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1392
Mathias Agopianda27af92012-09-13 18:17:13 -07001393 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394 }
1395 }
1396 }
1397
1398 postFramebuffer();
1399
1400 if (mDebugRegion > 1) {
1401 usleep(mDebugRegion * 1000);
1402 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001403
Dan Stoza9e56aa02015-11-02 13:00:03 -08001404 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001405 auto& displayDevice = mDisplays[displayId];
1406 if (!displayDevice->isDisplayOn()) {
1407 continue;
1408 }
1409
1410 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001411 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1412 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001413 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414}
1415
Brian Andersond6927fb2016-07-23 23:37:30 -07001416void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001417{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001418 ATRACE_CALL();
1419 ALOGV("preComposition");
1420
Mathias Agopiancd60f992012-08-16 16:28:27 -07001421 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001422 mDrawingState.traverseInZOrder([&](Layer* layer) {
1423 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424 needExtraInvalidate = true;
1425 }
Robert Carr2047fae2016-11-28 14:09:09 -08001426 });
1427
Mathias Agopiancd60f992012-08-16 16:28:27 -07001428 if (needExtraInvalidate) {
1429 signalLayerUpdate();
1430 }
1431}
1432
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001433void SurfaceFlinger::updateCompositorTiming(
1434 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1435 std::shared_ptr<FenceTime>& presentFenceTime) {
1436 // Update queue of past composite+present times and determine the
1437 // most recently known composite to present latency.
1438 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1439 nsecs_t compositeToPresentLatency = -1;
1440 while (!mCompositePresentTimes.empty()) {
1441 CompositePresentTime& cpt = mCompositePresentTimes.front();
1442 // Cached values should have been updated before calling this method,
1443 // which helps avoid duplicate syscalls.
1444 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1445 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1446 break;
1447 }
1448 compositeToPresentLatency = displayTime - cpt.composite;
1449 mCompositePresentTimes.pop();
1450 }
1451
1452 // Don't let mCompositePresentTimes grow unbounded, just in case.
1453 while (mCompositePresentTimes.size() > 16) {
1454 mCompositePresentTimes.pop();
1455 }
1456
Brian Andersond0010582017-03-07 13:20:31 -08001457 setCompositorTimingSnapped(
1458 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1459}
1460
1461void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1462 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001463 // Integer division and modulo round toward 0 not -inf, so we need to
1464 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001465 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001466 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1467 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1468
Brian Andersond0010582017-03-07 13:20:31 -08001469 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1470 if (idealLatency <= 0) {
1471 idealLatency = vsyncInterval;
1472 }
1473
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001474 // Snap the latency to a value that removes scheduling jitter from the
1475 // composition and present times, which often have >1ms of jitter.
1476 // Reducing jitter is important if an app attempts to extrapolate
1477 // something (such as user input) to an accurate diasplay time.
1478 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1479 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001480 nsecs_t bias = vsyncInterval / 2;
1481 int64_t extraVsyncs =
1482 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1483 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1484 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001485
Brian Andersond0010582017-03-07 13:20:31 -08001486 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001487 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1488 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001489 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001490}
1491
1492void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001494 ATRACE_CALL();
1495 ALOGV("postComposition");
1496
Brian Anderson3546a3f2016-07-14 11:51:14 -07001497 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001498 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001499 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001500 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001501 }
1502
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001503 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001504
1505 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1506 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1507 glCompositionDoneFenceTime =
1508 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1509 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1510 } else {
1511 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1512 }
1513 mGlCompositionDoneTimeline.updateSignalTimes();
1514
Brian Anderson4e606e32017-03-16 15:34:57 -07001515 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1516 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1517 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001518 mDisplayTimeline.updateSignalTimes();
1519
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001520 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1521 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1522
1523 // We use the refreshStartTime which might be sampled a little later than
1524 // when we started doing work for this frame, but that should be okay
1525 // since updateCompositorTiming has snapping logic.
1526 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001527 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001528 CompositorTiming compositorTiming;
1529 {
1530 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1531 compositorTiming = mCompositorTiming;
1532 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001533
Robert Carr2047fae2016-11-28 14:09:09 -08001534 mDrawingState.traverseInZOrder([&](Layer* layer) {
1535 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001536 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001537 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001538 recordBufferingStats(layer->getName().string(),
1539 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001540 }
Robert Carr2047fae2016-11-28 14:09:09 -08001541 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001542
Brian Anderson4e606e32017-03-16 15:34:57 -07001543 if (presentFence->isValid()) {
1544 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001545 enableHardwareVsync();
1546 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001547 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001548 }
1549 }
1550
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001551 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001552 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001553 enableHardwareVsync();
1554 }
1555 }
1556
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001557 if (mAnimCompositionPending) {
1558 mAnimCompositionPending = false;
1559
Brian Anderson4e606e32017-03-16 15:34:57 -07001560 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001561 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001562 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001563 } else {
1564 // The HWC doesn't support present fences, so use the refresh
1565 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001566 nsecs_t presentTime =
1567 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001568 mAnimFrameTracker.setActualPresentTime(presentTime);
1569 }
1570 mAnimFrameTracker.advanceFrame();
1571 }
Dan Stozab90cf072015-03-05 11:05:59 -08001572
1573 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1574 return;
1575 }
1576
1577 nsecs_t currentTime = systemTime();
1578 if (mHasPoweredOff) {
1579 mHasPoweredOff = false;
1580 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001581 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001583 if (numPeriods < NUM_BUCKETS - 1) {
1584 mFrameBuckets[numPeriods] += elapsedTime;
1585 } else {
1586 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1587 }
1588 mTotalTime += elapsedTime;
1589 }
1590 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591}
1592
1593void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001594 ATRACE_CALL();
1595 ALOGV("rebuildLayerStacks");
1596
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001598 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1599 ATRACE_CALL();
1600 mVisibleRegionsDirty = false;
1601 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001602
Jeff Sharkey76488112017-02-27 14:15:18 -07001603 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1604 Region opaqueRegion;
1605 Region dirtyRegion;
1606 Vector<sp<Layer>> layersSortedByZ;
1607 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1608 const Transform& tr(displayDevice->getTransform());
1609 const Rect bounds(displayDevice->getBounds());
1610 if (displayDevice->isDisplayOn()) {
1611 computeVisibleRegions(
1612 displayDevice->getLayerStack(), dirtyRegion,
1613 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001614
Jeff Sharkey76488112017-02-27 14:15:18 -07001615 mDrawingState.traverseInZOrder([&](Layer* layer) {
1616 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1617 Region drawRegion(tr.transform(
1618 layer->visibleNonTransparentRegion));
1619 drawRegion.andSelf(bounds);
1620 if (!drawRegion.isEmpty()) {
1621 layersSortedByZ.add(layer);
1622 } else {
1623 // Clear out the HWC layer if this layer was
1624 // previously visible, but no longer is
1625 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1626 nullptr);
1627 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001628 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001629 // WM changes displayDevice->layerStack upon sleep/awake.
1630 // Here we make sure we delete the HWC layers even if
1631 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001632 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1633 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001634 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001635 });
1636 }
1637 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1638 displayDevice->undefinedRegion.set(bounds);
1639 displayDevice->undefinedRegion.subtractSelf(
1640 tr.transform(opaqueRegion));
1641 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001642 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001643 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001644}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001645
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001646// pickColorMode translates a given dataspace into the best available color mode.
1647// Currently only support sRGB and Display-P3.
1648android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1649 switch (dataSpace) {
1650 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1651 // system expects.
1652 case HAL_DATASPACE_UNKNOWN:
1653 case HAL_DATASPACE_SRGB:
1654 case HAL_DATASPACE_V0_SRGB:
1655 return HAL_COLOR_MODE_SRGB;
1656 break;
1657
1658 case HAL_DATASPACE_DISPLAY_P3:
1659 return HAL_COLOR_MODE_DISPLAY_P3;
1660 break;
1661
1662 default:
1663 // TODO (courtneygo): Do we want to assert an error here?
1664 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1665 dataSpace);
1666 return HAL_COLOR_MODE_SRGB;
1667 break;
1668 }
1669}
1670
1671android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1672 // Only support sRGB and Display-P3 right now.
1673 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1674 return HAL_DATASPACE_DISPLAY_P3;
1675 }
1676 return HAL_DATASPACE_V0_SRGB;
1677}
1678
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001680 ATRACE_CALL();
1681 ALOGV("setUpHWComposer");
1682
Jesse Hall028dc8f2013-08-20 16:35:32 -07001683 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001684 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1685 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1686 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1687
1688 // If nothing has changed (!dirty), don't recompose.
1689 // If something changed, but we don't currently have any visible layers,
1690 // and didn't when we last did a composition, then skip it this time.
1691 // The second rule does two things:
1692 // - When all layers are removed from a display, we'll emit one black
1693 // frame, then nothing more until we get new layers.
1694 // - When a display is created with a private layer stack, we won't
1695 // emit any black frames until a layer is added to the layer stack.
1696 bool mustRecompose = dirty && !(empty && wasEmpty);
1697
1698 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1699 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1700 mustRecompose ? "doing" : "skipping",
1701 dirty ? "+" : "-",
1702 empty ? "+" : "-",
1703 wasEmpty ? "+" : "-");
1704
Dan Stoza71433162014-02-04 16:22:36 -08001705 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001706
1707 if (mustRecompose) {
1708 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1709 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001710 }
1711
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712 // build the h/w work list
1713 if (CC_UNLIKELY(mGeometryInvalid)) {
1714 mGeometryInvalid = false;
1715 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1716 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1717 const auto hwcId = displayDevice->getHwcDisplayId();
1718 if (hwcId >= 0) {
1719 const Vector<sp<Layer>>& currentLayers(
1720 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001721 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001722 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001723 if (!layer->hasHwcLayer(hwcId)) {
1724 auto hwcLayer = mHwc->createLayer(hwcId);
1725 if (hwcLayer) {
1726 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1727 } else {
1728 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001730 }
1731 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001732
Robert Carrae060832016-11-28 10:51:00 -08001733 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001734 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001735 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001736 }
1737 }
1738 }
1739 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 }
Riley Andrews03414a12014-07-01 14:22:59 -07001741
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001742
1743 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1744
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 // Set the per-frame data
1746 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1747 auto& displayDevice = mDisplays[displayId];
1748 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001749
Dan Stoza9e56aa02015-11-02 13:00:03 -08001750 if (hwcId < 0) {
1751 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001752 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001753 if (colorMatrix != mPreviousColorMatrix) {
1754 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1755 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1756 "display %zd: %d", displayId, result);
1757 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1759 layer->setPerFrameData(displayDevice);
1760 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001761
1762 if (hasWideColorDisplay) {
1763 android_color_mode newColorMode;
1764 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1765
1766 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1767 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1768 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1769 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1770 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1771 }
1772 newColorMode = pickColorMode(newDataSpace);
1773
1774 setActiveColorModeInternal(displayDevice, newColorMode);
1775 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001776 }
1777
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001778 mPreviousColorMatrix = colorMatrix;
1779
Dan Stoza9e56aa02015-11-02 13:00:03 -08001780 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001781 auto& displayDevice = mDisplays[displayId];
1782 if (!displayDevice->isDisplayOn()) {
1783 continue;
1784 }
1785
1786 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001787 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1788 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001789 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001791
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792void SurfaceFlinger::doComposition() {
1793 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001794 ALOGV("doComposition");
1795
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001796 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001797 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001798 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001799 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001800 // transform the dirty region into this screen's coordinate space
1801 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001802
1803 // repaint the framebuffer (if needed)
1804 doDisplayComposition(hw, dirtyRegion);
1805
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806 hw->dirtyRegion.clear();
1807 hw->flip(hw->swapRegion);
1808 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001809 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001810 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001811 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001812}
1813
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814void SurfaceFlinger::postFramebuffer()
1815{
Mathias Agopian841cde52012-03-01 15:44:37 -08001816 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001818
Mathias Agopiana44b0412011-10-16 18:46:35 -07001819 const nsecs_t now = systemTime();
1820 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001821
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1823 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001824 if (!displayDevice->isDisplayOn()) {
1825 continue;
1826 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001827 const auto hwcId = displayDevice->getHwcDisplayId();
1828 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001829 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001830 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001831 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001832 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1834 sp<Fence> releaseFence = Fence::NO_FENCE;
1835 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1836 releaseFence = displayDevice->getClientTargetAcquireFence();
1837 } else {
1838 auto hwcLayer = layer->getHwcLayer(hwcId);
1839 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001840 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 layer->onLayerDisplayed(releaseFence);
1842 }
1843 if (hwcId >= 0) {
1844 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001845 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001846 }
1847
Mathias Agopiana44b0412011-10-16 18:46:35 -07001848 mLastSwapBufferTime = systemTime() - now;
1849 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001850
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001851 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001852 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1853 logFrameStats();
1854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001855}
1856
Mathias Agopian87baae12012-07-31 12:38:26 -07001857void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001858{
Mathias Agopian841cde52012-03-01 15:44:37 -08001859 ATRACE_CALL();
1860
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001861 // here we keep a copy of the drawing state (that is the state that's
1862 // going to be overwritten by handleTransactionLocked()) outside of
1863 // mStateLock so that the side-effects of the State assignment
1864 // don't happen with mStateLock held (which can cause deadlocks).
1865 State drawingState(mDrawingState);
1866
Mathias Agopianca4d3602011-05-19 15:38:14 -07001867 Mutex::Autolock _l(mStateLock);
1868 const nsecs_t now = systemTime();
1869 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001870
Mathias Agopianca4d3602011-05-19 15:38:14 -07001871 // Here we're guaranteed that some transaction flags are set
1872 // so we can call handleTransactionLocked() unconditionally.
1873 // We call getTransactionFlags(), which will also clear the flags,
1874 // with mStateLock held to guarantee that mCurrentState won't change
1875 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001876
Mathias Agopiane57f2922012-08-09 16:29:12 -07001877 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001878 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001879
Mathias Agopianca4d3602011-05-19 15:38:14 -07001880 mLastTransactionTime = systemTime() - now;
1881 mDebugInTransaction = 0;
1882 invalidateHwcGeometry();
1883 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001884}
1885
Mathias Agopian87baae12012-07-31 12:38:26 -07001886void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001887{
Dan Stoza7dde5992015-05-22 09:51:44 -07001888 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001889 mCurrentState.traverseInZOrder([](Layer* layer) {
1890 layer->notifyAvailableFrames();
1891 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001892
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 /*
1894 * Traversal of the children
1895 * (perform the transaction for each of them if needed)
1896 */
1897
Mathias Agopian3559b072012-08-15 13:46:03 -07001898 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001899 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001900 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001901 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001902
1903 const uint32_t flags = layer->doTransaction(0);
1904 if (flags & Layer::eVisibleRegion)
1905 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001906 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001907 }
1908
1909 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001910 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911 */
1912
Mathias Agopiane57f2922012-08-09 16:29:12 -07001913 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001914 // here we take advantage of Vector's copy-on-write semantics to
1915 // improve performance by skipping the transaction entirely when
1916 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001917 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1918 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001919 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001920 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001921 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001922 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001923
1924 // find the displays that were removed
1925 // (ie: in drawing state but not in current state)
1926 // also handle displays that changed
1927 // (ie: displays that are in both lists)
1928 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001929 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1930 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001931 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001932 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001933 // Call makeCurrent() on the primary display so we can
1934 // be sure that nothing associated with this display
1935 // is current.
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00001936 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001937 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001938 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1939 if (hw != NULL)
1940 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001941 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001942 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001943 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001944 } else {
1945 ALOGW("trying to remove the main display");
1946 }
1947 } else {
1948 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001949 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001950 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001951 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1952 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001953 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001954 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001955 // recreating the DisplayDevice, so we just remove it
1956 // from the drawing state, so that it get re-added
1957 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001958 sp<DisplayDevice> hw(getDisplayDevice(display));
1959 if (hw != NULL)
1960 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001961 mDisplays.removeItem(display);
1962 mDrawingState.displays.removeItemsAt(i);
1963 dc--; i--;
1964 // at this point we must loop to the next item
1965 continue;
1966 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001967
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001968 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001969 if (disp != NULL) {
1970 if (state.layerStack != draw[i].layerStack) {
1971 disp->setLayerStack(state.layerStack);
1972 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001973 if ((state.orientation != draw[i].orientation)
1974 || (state.viewport != draw[i].viewport)
1975 || (state.frame != draw[i].frame))
1976 {
1977 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001978 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001979 }
Michael Lentine47e45402014-07-18 15:34:25 -07001980 if (state.width != draw[i].width || state.height != draw[i].height) {
1981 disp->setDisplaySize(state.width, state.height);
1982 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001983 }
1984 }
1985 }
1986
1987 // find displays that were added
1988 // (ie: in current state but not in drawing state)
1989 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001990 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001991 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001992
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001993 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001994 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001995 sp<IGraphicBufferProducer> bqProducer;
1996 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00001997 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1998 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001999
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002001 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002002 // Virtual displays without a surface are dormant:
2003 // they have external state (layer stack, projection,
2004 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002005 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002006
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002007 // Allow VR composer to use virtual displays.
2008 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002009 int width = 0;
2010 int status = state.surface->query(
2011 NATIVE_WINDOW_WIDTH, &width);
2012 ALOGE_IF(status != NO_ERROR,
2013 "Unable to query width (%d)", status);
2014 int height = 0;
2015 status = state.surface->query(
2016 NATIVE_WINDOW_HEIGHT, &height);
2017 ALOGE_IF(status != NO_ERROR,
2018 "Unable to query height (%d)", status);
2019 int intFormat = 0;
2020 status = state.surface->query(
2021 NATIVE_WINDOW_FORMAT, &intFormat);
2022 ALOGE_IF(status != NO_ERROR,
2023 "Unable to query format (%d)", status);
2024 auto format = static_cast<android_pixel_format_t>(
2025 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002026
Dan Stoza8cf150a2016-08-02 10:27:31 -07002027 mHwc->allocateVirtualDisplay(width, height, &format,
2028 &hwcId);
2029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030
Dan Stoza5cf424b2016-05-20 14:02:39 -07002031 // TODO: Plumb requested format back up to consumer
2032
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 sp<VirtualDisplaySurface> vds =
2034 new VirtualDisplaySurface(*mHwc,
2035 hwcId, state.surface, bqProducer,
2036 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002037
2038 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002039 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002040 }
2041 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002042 ALOGE_IF(state.surface!=NULL,
2043 "adding a supported display, but rendering "
2044 "surface is provided (%p), ignoring it",
2045 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002046
2047 hwcId = state.type;
2048 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2049 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002050 }
2051
2052 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002053 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002054 sp<DisplayDevice> hw =
2055 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2056 dispSurface, producer,
2057 mRenderEngine->getEGLConfig(),
2058 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002059 hw->setLayerStack(state.layerStack);
2060 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002061 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002062 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002063 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002065 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002066 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002067 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002068 }
2069 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002071 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002072
Mathias Agopian84300952012-11-21 16:02:13 -08002073 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2074 // The transform hint might have changed for some layers
2075 // (either because a display has changed, or because a layer
2076 // as changed).
2077 //
2078 // Walk through all the layers in currentLayers,
2079 // and update their transform hint.
2080 //
2081 // If a layer is visible only on a single display, then that
2082 // display is used to calculate the hint, otherwise we use the
2083 // default display.
2084 //
2085 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2086 // the hint is set before we acquire a buffer from the surface texture.
2087 //
2088 // NOTE: layer transactions have taken place already, so we use their
2089 // drawing state. However, SurfaceFlinger's own transaction has not
2090 // happened yet, so we must use the current state layer list
2091 // (soon to become the drawing state list).
2092 //
2093 sp<const DisplayDevice> disp;
2094 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002095 bool first = true;
2096 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002097 // NOTE: we rely on the fact that layers are sorted by
2098 // layerStack first (so we don't have to traverse the list
2099 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002100 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002101 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002102 currentlayerStack = layerStack;
2103 // figure out if this layerstack is mirrored
2104 // (more than one display) if so, pick the default display,
2105 // if not, pick the only display it's on.
2106 disp.clear();
2107 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2108 sp<const DisplayDevice> hw(mDisplays[dpy]);
2109 if (hw->getLayerStack() == currentlayerStack) {
2110 if (disp == NULL) {
2111 disp = hw;
2112 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002113 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002114 break;
2115 }
2116 }
2117 }
2118 }
Chet Haase91d25932013-04-11 15:24:55 -07002119 if (disp == NULL) {
2120 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2121 // redraw after transform hint changes. See bug 8508397.
2122
2123 // could be null when this layer is using a layerStack
2124 // that is not visible on any display. Also can occur at
2125 // screen off/on times.
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00002126 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002127 }
Chet Haase91d25932013-04-11 15:24:55 -07002128 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002129
2130 first = false;
2131 });
Mathias Agopian84300952012-11-21 16:02:13 -08002132 }
2133
2134
Mathias Agopian3559b072012-08-15 13:46:03 -07002135 /*
2136 * Perform our own transaction if needed
2137 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002138
2139 if (mLayersAdded) {
2140 mLayersAdded = false;
2141 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002142 mVisibleRegionsDirty = true;
2143 }
2144
2145 // some layers might have been removed, so
2146 // we need to update the regions they're exposing.
2147 if (mLayersRemoved) {
2148 mLayersRemoved = false;
2149 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002150 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002151 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002152 // this layer is not visible anymore
2153 // TODO: we could traverse the tree from front to back and
2154 // compute the actual visible region
2155 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002156 Region visibleReg;
2157 visibleReg.set(layer->computeScreenBounds());
2158 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002159 }
Robert Carr2047fae2016-11-28 14:09:09 -08002160 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002161 }
2162
2163 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002164
2165 updateCursorAsync();
2166}
2167
2168void SurfaceFlinger::updateCursorAsync()
2169{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2171 auto& displayDevice = mDisplays[displayId];
2172 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002173 continue;
2174 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175
2176 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2177 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002178 }
2179 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002180}
2181
2182void SurfaceFlinger::commitTransaction()
2183{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002184 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002185 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002186 for (const auto& l : mLayersPendingRemoval) {
2187 recordBufferingStats(l->getName().string(),
2188 l->getOccupancyHistory(true));
2189 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190 }
2191 mLayersPendingRemoval.clear();
2192 }
2193
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002194 // If this transaction is part of a window animation then the next frame
2195 // we composite should be considered an animation as well.
2196 mAnimCompositionPending = mAnimTransactionPending;
2197
Mathias Agopian4fec8732012-06-29 14:12:52 -07002198 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002199 mDrawingState.traverseInZOrder([](Layer* layer) {
2200 layer->commitChildList();
2201 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002202 mTransactionPending = false;
2203 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002204 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002205}
2206
Robert Carr2047fae2016-11-28 14:09:09 -08002207void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002208 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209{
Mathias Agopian841cde52012-03-01 15:44:37 -08002210 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002212
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213 Region aboveOpaqueLayers;
2214 Region aboveCoveredLayers;
2215 Region dirty;
2216
Mathias Agopian87baae12012-07-31 12:38:26 -07002217 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218
Robert Carr2047fae2016-11-28 14:09:09 -08002219 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002220 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002221 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222
Jesse Hall01e29052013-02-19 16:13:35 -08002223 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002224 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002225 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002226
Mathias Agopianab028732010-03-16 16:41:46 -07002227 /*
2228 * opaqueRegion: area of a surface that is fully opaque.
2229 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002231
2232 /*
2233 * visibleRegion: area of a surface that is visible on screen
2234 * and not fully transparent. This is essentially the layer's
2235 * footprint minus the opaque regions above it.
2236 * Areas covered by a translucent surface are considered visible.
2237 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002239
2240 /*
2241 * coveredRegion: area of a surface that is covered by all
2242 * visible regions above it (which includes the translucent areas).
2243 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002245
Jesse Halla8026d22012-09-25 13:25:04 -07002246 /*
2247 * transparentRegion: area of a surface that is hinted to be completely
2248 * transparent. This is only used to tell when the layer has no visible
2249 * non-transparent regions and can be removed from the layer list. It
2250 * does not affect the visibleRegion of this layer or any layers
2251 * beneath it. The hint may not be correct if apps don't respect the
2252 * SurfaceView restrictions (which, sadly, some don't).
2253 */
2254 Region transparentRegion;
2255
Mathias Agopianab028732010-03-16 16:41:46 -07002256
2257 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002258 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002259 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002260 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002263 if (!visibleRegion.isEmpty()) {
2264 // Remove the transparent area from the visible region
2265 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002266 if (tr.preserveRects()) {
2267 // transform the transparent region
2268 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002269 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002270 // transformation too complex, can't do the
2271 // transparent region optimization.
2272 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002273 }
Mathias Agopianab028732010-03-16 16:41:46 -07002274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002275
Mathias Agopianab028732010-03-16 16:41:46 -07002276 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002279 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2280 // the opaque region is the layer's footprint
2281 opaqueRegion = visibleRegion;
2282 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283 }
2284 }
2285
Mathias Agopianab028732010-03-16 16:41:46 -07002286 // Clip the covered region to the visible region
2287 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2288
2289 // Update aboveCoveredLayers for next (lower) layer
2290 aboveCoveredLayers.orSelf(visibleRegion);
2291
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292 // subtract the opaque region covered by the layers above us
2293 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294
2295 // compute this layer's dirty region
2296 if (layer->contentDirty) {
2297 // we need to invalidate the whole region
2298 dirty = visibleRegion;
2299 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002300 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002301 layer->contentDirty = false;
2302 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002303 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002304 * the exposed region consists of two components:
2305 * 1) what's VISIBLE now and was COVERED before
2306 * 2) what's EXPOSED now less what was EXPOSED before
2307 *
2308 * note that (1) is conservative, we start with the whole
2309 * visible region but only keep what used to be covered by
2310 * something -- which mean it may have been exposed.
2311 *
2312 * (2) handles areas that were not covered by anything but got
2313 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002314 */
Mathias Agopianab028732010-03-16 16:41:46 -07002315 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002316 const Region oldVisibleRegion = layer->visibleRegion;
2317 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002318 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2319 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320 }
2321 dirty.subtractSelf(aboveOpaqueLayers);
2322
2323 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002324 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325
Mathias Agopianab028732010-03-16 16:41:46 -07002326 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002328
Jesse Halla8026d22012-09-25 13:25:04 -07002329 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330 layer->setVisibleRegion(visibleRegion);
2331 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002332 layer->setVisibleNonTransparentRegion(
2333 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002334 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335
Mathias Agopian87baae12012-07-31 12:38:26 -07002336 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337}
2338
Mathias Agopian87baae12012-07-31 12:38:26 -07002339void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2340 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002341 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002342 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2343 if (hw->getLayerStack() == layerStack) {
2344 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002345 }
2346 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002347}
2348
Dan Stoza6b9454d2014-11-07 16:00:59 -08002349bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002351 ALOGV("handlePageFlip");
2352
Brian Andersond6927fb2016-07-23 23:37:30 -07002353 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354
Mathias Agopian4fec8732012-06-29 14:12:52 -07002355 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002356 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002357
2358 // Store the set of layers that need updates. This set must not change as
2359 // buffers are being latched, as this could result in a deadlock.
2360 // Example: Two producers share the same command stream and:
2361 // 1.) Layer 0 is latched
2362 // 2.) Layer 0 gets a new frame
2363 // 2.) Layer 1 gets a new frame
2364 // 3.) Layer 1 is latched.
2365 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2366 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002367 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002368 if (layer->hasQueuedFrame()) {
2369 frameQueued = true;
2370 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002371 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002372 } else {
2373 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002374 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002375 } else {
2376 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002377 }
Robert Carr2047fae2016-11-28 14:09:09 -08002378 });
2379
Dan Stoza9e56aa02015-11-02 13:00:03 -08002380 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002381 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002382 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002383 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002384 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002385
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002386 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002387
2388 // If we will need to wake up at some time in the future to deal with a
2389 // queued frame that shouldn't be displayed during this vsync period, wake
2390 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002391 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002392 signalLayerUpdate();
2393 }
2394
2395 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002396 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397}
2398
Mathias Agopianad456f92011-01-13 17:53:01 -08002399void SurfaceFlinger::invalidateHwcGeometry()
2400{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002401 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002402}
2403
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002404
Fabien Sanglard830b8472016-11-30 16:35:58 -08002405void SurfaceFlinger::doDisplayComposition(
2406 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002407 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408{
Dan Stoza71433162014-02-04 16:22:36 -08002409 // We only need to actually compose the display if:
2410 // 1) It is being handled by hardware composer, which may need this to
2411 // keep its virtual display state machine in sync, or
2412 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002413 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002414 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002415 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002416 return;
2417 }
2418
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 ALOGV("doDisplayComposition");
2420
Mathias Agopian87baae12012-07-31 12:38:26 -07002421 Region dirtyRegion(inDirtyRegion);
2422
Mathias Agopianb8a55602009-06-26 19:06:36 -07002423 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002424 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425
Fabien Sanglard830b8472016-11-30 16:35:58 -08002426 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002427 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002428 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2429 // takes a rectangle, we must make sure to update that whole
2430 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002431 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002432 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002433 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002434 // We need to redraw the rectangle that will be updated
2435 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002436 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002437 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002438 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002439 } else {
2440 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002441 dirtyRegion.set(displayDevice->bounds());
2442 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443 }
2444 }
2445
Fabien Sanglard830b8472016-11-30 16:35:58 -08002446 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002447
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002448 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002449 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002450
2451 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002452 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453}
2454
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455bool SurfaceFlinger::doComposeSurfaces(
2456 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002457{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002459
Dan Stoza9e56aa02015-11-02 13:00:03 -08002460 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002461
2462 mat4 oldColorMatrix;
2463 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2464 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2465 if (applyColorMatrix) {
2466 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2467 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2468 }
2469
Dan Stoza9e56aa02015-11-02 13:00:03 -08002470 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2471 if (hasClientComposition) {
2472 ALOGV("hasClientComposition");
2473
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002474#ifdef USE_HWC2
2475 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2476 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2477#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002479 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002481 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00002482 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002483 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2484 }
2485 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002486 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002487
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002488 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2490 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002491 // when using overlays, we assume a fully transparent framebuffer
2492 // NOTE: we could reduce how much we need to clear, for instance
2493 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002494 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002495 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002497 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002498 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002500
2501 // we remove the scissor part
2502 // we're left with the letterbox region
2503 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002504 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002505
2506 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002507 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002508
2509 // but limit it to the dirty region
2510 region.andSelf(dirty);
2511
Mathias Agopianb9494d52012-04-18 02:28:45 -07002512 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002513 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002514 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002516 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002517 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002518
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002520 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002521 // scissor on the main display. It should never be needed
2522 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 const Rect& bounds(displayDevice->getBounds());
2524 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002525 if (scissor != bounds) {
2526 // scissor doesn't match the screen's dimensions, so we
2527 // need to clear everything outside of it and enable
2528 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002529
Mathias Agopianf45c5102012-10-24 16:29:17 -07002530 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 const uint32_t height = displayDevice->getHeight();
2532 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002533 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002534 }
2535 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002536 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002537
Mathias Agopian85d751c2012-08-29 16:59:24 -07002538 /*
2539 * and then, render the layers targeted at the framebuffer
2540 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002541
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 ALOGV("Rendering client layers");
2543 const Transform& displayTransform = displayDevice->getTransform();
2544 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002545 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 bool firstLayer = true;
2547 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2548 const Region clip(dirty.intersect(
2549 displayTransform.transform(layer->visibleRegion)));
2550 ALOGV("Layer: %s", layer->getName().string());
2551 ALOGV(" Composition type: %s",
2552 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002553 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554 switch (layer->getCompositionType(hwcId)) {
2555 case HWC2::Composition::Cursor:
2556 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002557 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002559 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2561 layer->isOpaque(state) && (state.alpha == 1.0f)
2562 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002563 // never clear the very first layer since we're
2564 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002565 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002566 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002567 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002568 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 case HWC2::Composition::Client: {
2570 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002571 break;
2572 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002574 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002575 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576 } else {
2577 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002578 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002580 }
2581 } else {
2582 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002583 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002584 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002586 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002588 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002589 }
2590 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002591
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002592 if (applyColorMatrix) {
2593 getRenderEngine().setupColorTransform(oldColorMatrix);
2594 }
2595
Mathias Agopianf45c5102012-10-24 16:29:17 -07002596 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002598 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599}
2600
Fabien Sanglard830b8472016-11-30 16:35:58 -08002601void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2602 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002603 RenderEngine& engine(getRenderEngine());
2604 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002605}
2606
Dan Stoza7d89d062015-04-30 13:29:25 -07002607status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002608 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002609 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002610 const sp<Layer>& lbc,
2611 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002612{
Dan Stoza7d89d062015-04-30 13:29:25 -07002613 // add this layer to the current state list
2614 {
2615 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002616 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002617 return NO_MEMORY;
2618 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619 if (parent == nullptr) {
2620 mCurrentState.layersSortedByZ.add(lbc);
2621 } else {
2622 parent->addChild(lbc);
2623 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002624 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002625 mLayersAdded = true;
2626 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002627 }
2628
Mathias Agopian96f08192010-06-02 23:28:45 -07002629 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002630 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002631
Dan Stoza7d89d062015-04-30 13:29:25 -07002632 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002633}
2634
Robert Carr9524cb32017-02-13 11:32:32 -08002635status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002636 Mutex::Autolock _l(mStateLock);
2637
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 const auto& p = layer->getParent();
2639 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2640 mCurrentState.layersSortedByZ.remove(layer);
2641
Robert Carr136e2f62017-02-08 17:54:29 -08002642 // As a matter of normal operation, the LayerCleaner will produce a second
2643 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2644 // so we will succeed in promoting it, but it's already been removed
2645 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2646 // otherwise something has gone wrong and we are leaking the layer.
2647 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002648 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2649 layer->getName().string(),
2650 (p != nullptr) ? p->getName().string() : "no-parent");
2651 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002652 } else if (index < 0) {
2653 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002654 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655
2656 mLayersPendingRemoval.add(layer);
2657 mLayersRemoved = true;
2658 mNumLayers--;
2659 setTransactionFlags(eTransactionNeeded);
2660 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002661}
2662
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002663uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002664 return android_atomic_release_load(&mTransactionFlags);
2665}
2666
Mathias Agopian3f844832013-08-07 21:24:32 -07002667uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2669}
2670
Mathias Agopian3f844832013-08-07 21:24:32 -07002671uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2673 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002674 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 }
2676 return old;
2677}
2678
Mathias Agopian8b33f032012-07-24 20:43:54 -07002679void SurfaceFlinger::setTransactionState(
2680 const Vector<ComposerState>& state,
2681 const Vector<DisplayState>& displays,
2682 uint32_t flags)
2683{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002684 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002685 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002686 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002687
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002688 if (flags & eAnimation) {
2689 // For window updates that are part of an animation we must wait for
2690 // previous animation "frames" to be handled.
2691 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002692 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002693 if (CC_UNLIKELY(err != NO_ERROR)) {
2694 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002695 // caller after a few seconds.
2696 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2697 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002698 mAnimTransactionPending = false;
2699 break;
2700 }
2701 }
2702 }
2703
Mathias Agopiane57f2922012-08-09 16:29:12 -07002704 size_t count = displays.size();
2705 for (size_t i=0 ; i<count ; i++) {
2706 const DisplayState& s(displays[i]);
2707 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002708 }
2709
Mathias Agopiane57f2922012-08-09 16:29:12 -07002710 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002711 for (size_t i=0 ; i<count ; i++) {
2712 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002713 // Here we need to check that the interface we're given is indeed
2714 // one of our own. A malicious client could give us a NULL
2715 // IInterface, or one of its own or even one of our own but a
2716 // different type. All these situations would cause us to crash.
2717 //
2718 // NOTE: it would be better to use RTTI as we could directly check
2719 // that we have a Client*. however, RTTI is disabled in Android.
2720 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002721 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002722 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002723 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002724 sp<Client> client( static_cast<Client *>(s.client.get()) );
2725 transactionFlags |= setClientStateLocked(client, s.state);
2726 }
2727 }
2728 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002729 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002730
Robert Carr2a7dbb42016-05-24 11:41:28 -07002731 // If a synchronous transaction is explicitly requested without any changes,
2732 // force a transaction anyway. This can be used as a flush mechanism for
2733 // previous async transactions.
2734 if (transactionFlags == 0 && (flags & eSynchronous)) {
2735 transactionFlags = eTransactionNeeded;
2736 }
2737
Mathias Agopian386aa982011-11-07 21:58:03 -08002738 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002739 if (mInterceptor.isEnabled()) {
2740 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2741 }
Irvel468051e2016-06-13 16:44:44 -07002742
Mathias Agopian386aa982011-11-07 21:58:03 -08002743 // this triggers the transaction
2744 setTransactionFlags(transactionFlags);
2745
2746 // if this is a synchronous transaction, wait for it to take effect
2747 // before returning.
2748 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002749 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002750 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002751 if (flags & eAnimation) {
2752 mAnimTransactionPending = true;
2753 }
2754 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002755 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2756 if (CC_UNLIKELY(err != NO_ERROR)) {
2757 // just in case something goes wrong in SF, return to the
2758 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002759 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2760 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002761 break;
2762 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002763 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 }
2765}
2766
Mathias Agopiane57f2922012-08-09 16:29:12 -07002767uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2768{
Jesse Hall9a143922012-10-04 16:29:19 -07002769 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2770 if (dpyIdx < 0)
2771 return 0;
2772
Mathias Agopiane57f2922012-08-09 16:29:12 -07002773 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002774 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002775 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002776 const uint32_t what = s.what;
2777 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002778 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002779 disp.surface = s.surface;
2780 flags |= eDisplayTransactionNeeded;
2781 }
2782 }
2783 if (what & DisplayState::eLayerStackChanged) {
2784 if (disp.layerStack != s.layerStack) {
2785 disp.layerStack = s.layerStack;
2786 flags |= eDisplayTransactionNeeded;
2787 }
2788 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002789 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002790 if (disp.orientation != s.orientation) {
2791 disp.orientation = s.orientation;
2792 flags |= eDisplayTransactionNeeded;
2793 }
2794 if (disp.frame != s.frame) {
2795 disp.frame = s.frame;
2796 flags |= eDisplayTransactionNeeded;
2797 }
2798 if (disp.viewport != s.viewport) {
2799 disp.viewport = s.viewport;
2800 flags |= eDisplayTransactionNeeded;
2801 }
2802 }
Michael Lentine47e45402014-07-18 15:34:25 -07002803 if (what & DisplayState::eDisplaySizeChanged) {
2804 if (disp.width != s.width) {
2805 disp.width = s.width;
2806 flags |= eDisplayTransactionNeeded;
2807 }
2808 if (disp.height != s.height) {
2809 disp.height = s.height;
2810 flags |= eDisplayTransactionNeeded;
2811 }
2812 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002813 }
2814 return flags;
2815}
2816
2817uint32_t SurfaceFlinger::setClientStateLocked(
2818 const sp<Client>& client,
2819 const layer_state_t& s)
2820{
2821 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002822 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002823 if (layer != 0) {
2824 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002825 bool geometryAppliesWithResize =
2826 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002827 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002828 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002829 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002830 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002831 }
2832 if (what & layer_state_t::eLayerChanged) {
2833 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002834 const auto& p = layer->getParent();
2835 if (p == nullptr) {
2836 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2837 if (layer->setLayer(s.z) && idx >= 0) {
2838 mCurrentState.layersSortedByZ.removeAt(idx);
2839 mCurrentState.layersSortedByZ.add(layer);
2840 // we need traversal (state changed)
2841 // AND transaction (list changed)
2842 flags |= eTransactionNeeded|eTraversalNeeded;
2843 }
2844 } else {
2845 if (p->setChildLayer(layer, s.z)) {
2846 flags |= eTransactionNeeded|eTraversalNeeded;
2847 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002848 }
2849 }
Robert Carrdb66e622017-04-10 16:55:57 -07002850 if (what & layer_state_t::eRelativeLayerChanged) {
2851 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2852 flags |= eTransactionNeeded|eTraversalNeeded;
2853 }
2854 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002855 if (what & layer_state_t::eSizeChanged) {
2856 if (layer->setSize(s.w, s.h)) {
2857 flags |= eTraversalNeeded;
2858 }
2859 }
2860 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002862 flags |= eTraversalNeeded;
2863 }
2864 if (what & layer_state_t::eMatrixChanged) {
2865 if (layer->setMatrix(s.matrix))
2866 flags |= eTraversalNeeded;
2867 }
2868 if (what & layer_state_t::eTransparentRegionChanged) {
2869 if (layer->setTransparentRegionHint(s.transparentRegion))
2870 flags |= eTraversalNeeded;
2871 }
Dan Stoza23116082015-06-18 14:58:39 -07002872 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002873 if (layer->setFlags(s.flags, s.mask))
2874 flags |= eTraversalNeeded;
2875 }
2876 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002877 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878 flags |= eTraversalNeeded;
2879 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002880 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002881 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002882 flags |= eTraversalNeeded;
2883 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002884 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002885 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 // We only allow setting layer stacks for top level layers,
2887 // everything else inherits layer stack from its parent.
2888 if (layer->hasParent()) {
2889 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2890 layer->getName().string());
2891 } else if (idx < 0) {
2892 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2893 "that also does not appear in the top level layer list. Something"
2894 " has gone wrong.", layer->getName().string());
2895 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002896 mCurrentState.layersSortedByZ.removeAt(idx);
2897 mCurrentState.layersSortedByZ.add(layer);
2898 // we need traversal (state changed)
2899 // AND transaction (list changed)
2900 flags |= eTransactionNeeded|eTraversalNeeded;
2901 }
2902 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002903 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002904 if (s.barrierHandle != nullptr) {
2905 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2906 } else if (s.barrierGbp != nullptr) {
2907 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2908 if (authenticateSurfaceTextureLocked(gbp)) {
2909 const auto& otherLayer =
2910 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2911 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2912 } else {
2913 ALOGE("Attempt to defer transaction to to an"
2914 " unrecognized GraphicBufferProducer");
2915 }
2916 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002917 // We don't trigger a traversal here because if no other state is
2918 // changed, we don't want this to cause any more work
2919 }
Robert Carr1db73f62016-12-21 12:58:51 -08002920 if (what & layer_state_t::eReparentChildren) {
2921 if (layer->reparentChildren(s.reparentHandle)) {
2922 flags |= eTransactionNeeded|eTraversalNeeded;
2923 }
2924 }
Robert Carr9524cb32017-02-13 11:32:32 -08002925 if (what & layer_state_t::eDetachChildren) {
2926 layer->detachChildren();
2927 }
Robert Carrc3574f72016-03-24 12:19:32 -07002928 if (what & layer_state_t::eOverrideScalingModeChanged) {
2929 layer->setOverrideScalingMode(s.overrideScalingMode);
2930 // We don't trigger a traversal here because if no other state is
2931 // changed, we don't want this to cause any more work
2932 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 }
2934 return flags;
2935}
2936
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002937status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002938 const String8& name,
2939 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002940 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002941 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2942 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002944 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002945 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002946 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002947 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002948 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002949
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002950 status_t result = NO_ERROR;
2951
2952 sp<Layer> layer;
2953
Cody Northropbc755282017-03-31 12:00:08 -06002954 String8 uniqueName = getUniqueLayerName(name);
2955
Mathias Agopian3165cc22012-08-08 19:42:09 -07002956 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2957 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002958 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002959 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002960 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002962 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002963 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002964 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002965 handle, gbp, &layer);
2966 break;
2967 default:
2968 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969 break;
2970 }
2971
Dan Stoza7d89d062015-04-30 13:29:25 -07002972 if (result != NO_ERROR) {
2973 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002974 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002975
Albert Chaulk479c60c2017-01-27 14:21:34 -05002976 layer->setInfo(windowType, ownerUid);
2977
Robert Carr1f0a16a2016-10-24 16:27:39 -07002978 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002979 if (result != NO_ERROR) {
2980 return result;
2981 }
Irvelffc9efc2016-07-27 15:16:37 -07002982 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002983
2984 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002985 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986}
2987
Cody Northropbc755282017-03-31 12:00:08 -06002988String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
2989{
2990 bool matchFound = true;
2991 uint32_t dupeCounter = 0;
2992
2993 // Tack on our counter whether there is a hit or not, so everyone gets a tag
2994 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
2995
2996 // Loop over layers until we're sure there is no matching name
2997 while (matchFound) {
2998 matchFound = false;
2999 mDrawingState.traverseInZOrder([&](Layer* layer) {
3000 if (layer->getName() == uniqueName) {
3001 matchFound = true;
3002 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3003 }
3004 });
3005 }
3006
3007 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3008
3009 return uniqueName;
3010}
3011
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003012status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3013 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3014 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003015{
3016 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003017 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018 case PIXEL_FORMAT_TRANSPARENT:
3019 case PIXEL_FORMAT_TRANSLUCENT:
3020 format = PIXEL_FORMAT_RGBA_8888;
3021 break;
3022 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003023 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024 break;
3025 }
3026
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003027 *outLayer = new Layer(this, client, name, w, h, flags);
3028 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3029 if (err == NO_ERROR) {
3030 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003031 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003033
3034 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3035 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003036}
3037
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003038status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3039 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3040 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003041{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003042 *outLayer = new LayerDim(this, client, name, w, h, flags);
3043 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003044 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003045 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003046}
3047
Mathias Agopianac9fa422013-02-11 16:40:36 -08003048status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049{
Robert Carr9524cb32017-02-13 11:32:32 -08003050 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003051 status_t err = NO_ERROR;
3052 sp<Layer> l(client->getLayerUser(handle));
3053 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003054 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003055 err = removeLayer(l);
3056 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3057 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003058 }
3059 return err;
3060}
3061
Mathias Agopian13127d82013-03-05 17:47:11 -08003062status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003063{
Mathias Agopian67106042013-03-14 19:18:13 -07003064 // called by ~LayerCleaner() when all references to the IBinder (handle)
3065 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003066 sp<Layer> l = layer.promote();
3067 if (l == nullptr) {
3068 // The layer has already been removed, carry on
3069 return NO_ERROR;
3070 } if (l->getParent() != nullptr) {
3071 // If we have a parent, then we can continue to live as long as it does.
3072 return NO_ERROR;
3073 }
3074 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Mathias Agopianb60314a2012-04-10 22:09:54 -07003077// ---------------------------------------------------------------------------
3078
Andy McFadden13a082e2012-08-24 10:16:42 -07003079void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003080 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003081 Vector<ComposerState> state;
3082 Vector<DisplayState> displays;
3083 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003084 d.what = DisplayState::eDisplayProjectionChanged |
3085 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003086 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003087 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003088 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003089 d.frame.makeInvalid();
3090 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003091 d.width = 0;
3092 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003093 displays.add(d);
3094 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003095 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003096
Dan Stoza9e56aa02015-11-02 13:00:03 -08003097 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3098 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003099 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003100
Brian Andersond0010582017-03-07 13:20:31 -08003101 // Use phase of 0 since phase is not known.
3102 // Use latency of 0, which will snap to the ideal latency.
3103 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003104}
3105
3106void SurfaceFlinger::initializeDisplays() {
3107 class MessageScreenInitialized : public MessageBase {
3108 SurfaceFlinger* flinger;
3109 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003110 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003111 virtual bool handler() {
3112 flinger->onInitializeDisplays();
3113 return true;
3114 }
3115 };
3116 sp<MessageBase> msg = new MessageScreenInitialized(this);
3117 postMessageAsync(msg); // we may be called from main thread, use async message
3118}
3119
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003120void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3121 int mode) {
3122 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3123 this);
3124 int32_t type = hw->getDisplayType();
3125 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003126
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003127 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003128 return;
3129 }
3130
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003131 hw->setPowerMode(mode);
3132 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3133 ALOGW("Trying to set power mode for virtual display");
3134 return;
3135 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003136
Irvelffc9efc2016-07-27 15:16:37 -07003137 if (mInterceptor.isEnabled()) {
3138 Mutex::Autolock _l(mStateLock);
3139 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3140 if (idx < 0) {
3141 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3142 return;
3143 }
3144 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3145 }
3146
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003147 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003148 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003149 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003150 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3151 // FIXME: eventthread only knows about the main display right now
3152 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003153 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003154 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003156 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003157 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003158 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003159
3160 struct sched_param param = {0};
3161 param.sched_priority = 1;
3162 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3163 ALOGW("Couldn't set SCHED_FIFO on display on");
3164 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003165 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003166 // Turn off the display
3167 struct sched_param param = {0};
3168 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3169 ALOGW("Couldn't set SCHED_OTHER on display off");
3170 }
3171
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003172 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003173 disableHardwareVsync(true); // also cancels any in-progress resync
3174
Mathias Agopiancde87a32012-09-13 14:09:01 -07003175 // FIXME: eventthread only knows about the main display right now
3176 mEventThread->onScreenReleased();
3177 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003178
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003179 getHwComposer().setPowerMode(type, mode);
3180 mVisibleRegionsDirty = true;
3181 // from this point on, SF will stop drawing on this display
3182 } else {
3183 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003184 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003185}
3186
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003187void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3188 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003189 SurfaceFlinger& mFlinger;
3190 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003191 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003192 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003193 MessageSetPowerMode(SurfaceFlinger& flinger,
3194 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3195 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003196 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003197 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003198 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003199 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003200 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003201 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003202 ALOGW("Attempt to set power mode = %d for virtual display",
3203 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003204 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003205 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003206 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003207 return true;
3208 }
3209 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003210 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003211 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003212}
3213
3214// ---------------------------------------------------------------------------
3215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3217{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003219
Mathias Agopianbd115332013-04-18 16:41:04 -07003220 IPCThreadState* ipc = IPCThreadState::self();
3221 const int pid = ipc->getCallingPid();
3222 const int uid = ipc->getCallingUid();
3223 if ((uid != AID_SHELL) &&
3224 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003225 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003226 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003228 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003229 // (this would indicate SF is stuck, but we want to be able to
3230 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003231 status_t err = mStateLock.timedLock(s2ns(1));
3232 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003233 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003234 result.appendFormat(
3235 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3236 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003237 }
3238
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003239 bool dumpAll = true;
3240 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003241 size_t numArgs = args.size();
3242 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003243 if ((index < numArgs) &&
3244 (args[index] == String16("--list"))) {
3245 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003246 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003247 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003248 }
3249
3250 if ((index < numArgs) &&
3251 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003252 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003253 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003254 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003255 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003256
3257 if ((index < numArgs) &&
3258 (args[index] == String16("--latency-clear"))) {
3259 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003260 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003261 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003262 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003263
3264 if ((index < numArgs) &&
3265 (args[index] == String16("--dispsync"))) {
3266 index++;
3267 mPrimaryDispSync.dump(result);
3268 dumpAll = false;
3269 }
Dan Stozab90cf072015-03-05 11:05:59 -08003270
3271 if ((index < numArgs) &&
3272 (args[index] == String16("--static-screen"))) {
3273 index++;
3274 dumpStaticScreenStats(result);
3275 dumpAll = false;
3276 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003277
3278 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003279 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003280 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003281 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003282 dumpAll = false;
3283 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003284
3285 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3286 index++;
3287 dumpWideColorInfo(result);
3288 dumpAll = false;
3289 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003291
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003292 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003293 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003294 }
3295
Mathias Agopian9795c422009-08-26 16:36:26 -07003296 if (locked) {
3297 mStateLock.unlock();
3298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003299 }
3300 write(fd, result.string(), result.size());
3301 return NO_ERROR;
3302}
3303
Dan Stozac7014012014-02-14 15:03:43 -08003304void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3305 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003306{
Robert Carr2047fae2016-11-28 14:09:09 -08003307 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003308 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003309 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003310}
3311
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003312void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003313 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314{
3315 String8 name;
3316 if (index < args.size()) {
3317 name = String8(args[index]);
3318 index++;
3319 }
3320
Dan Stoza9e56aa02015-11-02 13:00:03 -08003321 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3322 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003323 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003324
3325 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003326 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003327 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003328 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003329 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003330 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003331 }
Robert Carr2047fae2016-11-28 14:09:09 -08003332 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003333 }
3334}
3335
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003336void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003337 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003338{
3339 String8 name;
3340 if (index < args.size()) {
3341 name = String8(args[index]);
3342 index++;
3343 }
3344
Robert Carr2047fae2016-11-28 14:09:09 -08003345 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003346 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003347 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003348 }
Robert Carr2047fae2016-11-28 14:09:09 -08003349 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003350
Svetoslavd85084b2014-03-20 10:28:31 -07003351 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003352}
3353
Jamie Gennis6547ff42013-07-16 20:12:42 -07003354// This should only be called from the main thread. Otherwise it would need
3355// the lock and should use mCurrentState rather than mDrawingState.
3356void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003357 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003358 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003359 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003360
3361 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3362}
3363
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003364void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003365{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003366 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003367 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3368
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003369 if (isLayerTripleBufferingDisabled())
3370 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003371
3372 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003373 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003374 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003375 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003376 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3377 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003378 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003379}
3380
Dan Stozab90cf072015-03-05 11:05:59 -08003381void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3382{
3383 result.appendFormat("Static screen stats:\n");
3384 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3385 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3386 float percent = 100.0f *
3387 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3388 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3389 b + 1, bucketTimeSec, percent);
3390 }
3391 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3392 float percent = 100.0f *
3393 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3394 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3395 NUM_BUCKETS - 1, bucketTimeSec, percent);
3396}
3397
Dan Stozae77c7662016-05-13 11:37:28 -07003398void SurfaceFlinger::recordBufferingStats(const char* layerName,
3399 std::vector<OccupancyTracker::Segment>&& history) {
3400 Mutex::Autolock lock(mBufferingStatsMutex);
3401 auto& stats = mBufferingStats[layerName];
3402 for (const auto& segment : history) {
3403 if (!segment.usedThirdBuffer) {
3404 stats.twoBufferTime += segment.totalTime;
3405 }
3406 if (segment.occupancyAverage < 1.0f) {
3407 stats.doubleBufferedTime += segment.totalTime;
3408 } else if (segment.occupancyAverage < 2.0f) {
3409 stats.tripleBufferedTime += segment.totalTime;
3410 }
3411 ++stats.numSegments;
3412 stats.totalTime += segment.totalTime;
3413 }
3414}
3415
Brian Andersond6927fb2016-07-23 23:37:30 -07003416void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3417 result.appendFormat("Layer frame timestamps:\n");
3418
3419 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3420 const size_t count = currentLayers.size();
3421 for (size_t i=0 ; i<count ; i++) {
3422 currentLayers[i]->dumpFrameEvents(result);
3423 }
3424}
3425
Dan Stozae77c7662016-05-13 11:37:28 -07003426void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3427 result.append("Buffering stats:\n");
3428 result.append(" [Layer name] <Active time> <Two buffer> "
3429 "<Double buffered> <Triple buffered>\n");
3430 Mutex::Autolock lock(mBufferingStatsMutex);
3431 typedef std::tuple<std::string, float, float, float> BufferTuple;
3432 std::map<float, BufferTuple, std::greater<float>> sorted;
3433 for (const auto& statsPair : mBufferingStats) {
3434 const char* name = statsPair.first.c_str();
3435 const BufferingStats& stats = statsPair.second;
3436 if (stats.numSegments == 0) {
3437 continue;
3438 }
3439 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3440 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3441 stats.totalTime;
3442 float doubleBufferRatio = static_cast<float>(
3443 stats.doubleBufferedTime) / stats.totalTime;
3444 float tripleBufferRatio = static_cast<float>(
3445 stats.tripleBufferedTime) / stats.totalTime;
3446 sorted.insert({activeTime, {name, twoBufferRatio,
3447 doubleBufferRatio, tripleBufferRatio}});
3448 }
3449 for (const auto& sortedPair : sorted) {
3450 float activeTime = sortedPair.first;
3451 const BufferTuple& values = sortedPair.second;
3452 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3453 std::get<0>(values).c_str(), activeTime,
3454 std::get<1>(values), std::get<2>(values),
3455 std::get<3>(values));
3456 }
3457 result.append("\n");
3458}
3459
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003460void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3461 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3462
3463 // TODO: print out if wide-color mode is active or not
3464
3465 for (size_t d = 0; d < mDisplays.size(); d++) {
3466 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3467 int32_t hwcId = displayDevice->getHwcDisplayId();
3468 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3469 continue;
3470 }
3471
3472 result.appendFormat("Display %d color modes:\n", hwcId);
3473 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3474 for (auto&& mode : modes) {
3475 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3476 }
3477
3478 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3479 result.appendFormat(" Current color mode: %s (%d)\n",
3480 decodeColorMode(currentMode).c_str(), currentMode);
3481 }
3482 result.append("\n");
3483}
3484
Mathias Agopian74d211a2013-04-22 16:55:35 +02003485void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3486 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003487{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003488 bool colorize = false;
3489 if (index < args.size()
3490 && (args[index] == String16("--color"))) {
3491 colorize = true;
3492 index++;
3493 }
3494
3495 Colorizer colorizer(colorize);
3496
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003497 // figure out if we're stuck somewhere
3498 const nsecs_t now = systemTime();
3499 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3500 const nsecs_t inTransaction(mDebugInTransaction);
3501 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3502 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3503
3504 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003505 * Dump library configuration.
3506 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003507
3508 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003509 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003510 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003511 appendSfConfigString(result);
3512 appendUiConfigString(result);
3513 appendGuiConfigString(result);
3514 result.append("\n");
3515
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003516 result.append("\nWide-Color information:\n");
3517 dumpWideColorInfo(result);
3518
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003519 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003520 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003521 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003522 result.append(SyncFeatures::getInstance().toString());
3523 result.append("\n");
3524
Dan Stoza9e56aa02015-11-02 13:00:03 -08003525 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3526
Andy McFadden41d67d72014-04-25 16:58:34 -07003527 colorizer.bold(result);
3528 result.append("DispSync configuration: ");
3529 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003530 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003531 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003532 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003533 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003534 result.append("\n");
3535
Dan Stozab90cf072015-03-05 11:05:59 -08003536 // Dump static screen stats
3537 result.append("\n");
3538 dumpStaticScreenStats(result);
3539 result.append("\n");
3540
Dan Stozae77c7662016-05-13 11:37:28 -07003541 dumpBufferingStats(result);
3542
Andy McFadden4803b742012-09-24 19:07:20 -07003543 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003544 * Dump the visible layer list
3545 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003546 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003547 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003548 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003549 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003550 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003551 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003552
3553 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003554 * Dump Display state
3555 */
3556
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003557 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003558 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003559 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003560 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3561 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003562 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003563 }
3564
3565 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003566 * Dump SurfaceFlinger global state
3567 */
3568
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003569 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003570 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003571 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003572
Mathias Agopian888c8222012-08-04 21:10:38 -07003573 HWComposer& hwc(getHwComposer());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003574 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003575
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003576 colorizer.bold(result);
3577 result.appendFormat("EGL implementation : %s\n",
3578 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3579 colorizer.reset(result);
3580 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003581 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003582
Mathias Agopian875d8e12013-06-07 15:35:48 -07003583 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003584
Mathias Agopian42977342012-08-05 00:40:46 -07003585 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003586 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3587 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003588 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003589 " last eglSwapBuffers() time: %f us\n"
3590 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003591 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003592 " refresh-rate : %f fps\n"
3593 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003594 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003595 " gpu_to_cpu_unsupported : %d\n"
3596 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003597 mLastSwapBufferTime/1000.0,
3598 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003599 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003600 1e9 / activeConfig->getVsyncPeriod(),
3601 activeConfig->getDpiX(),
3602 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003603 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003604
Mathias Agopian74d211a2013-04-22 16:55:35 +02003605 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003606 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003607
Mathias Agopian74d211a2013-04-22 16:55:35 +02003608 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003609 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610
3611 /*
3612 * VSYNC state
3613 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003614 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003615 result.append("\n");
3616
3617 /*
3618 * HWC layer minidump
3619 */
3620 for (size_t d = 0; d < mDisplays.size(); d++) {
3621 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3622 int32_t hwcId = displayDevice->getHwcDisplayId();
3623 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3624 continue;
3625 }
3626
3627 result.appendFormat("Display %d HWC layers:\n", hwcId);
3628 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003629 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003630 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003631 });
Dan Stozae22aec72016-08-01 13:20:59 -07003632 result.append("\n");
3633 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003634
3635 /*
3636 * Dump HWComposer state
3637 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003638 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003639 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003640 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003641 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003642 result.appendFormat(" h/w composer %s\n",
3643 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003644 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003645
3646 /*
3647 * Dump gralloc state
3648 */
3649 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3650 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003651}
3652
Mathias Agopian13127d82013-03-05 17:47:11 -08003653const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003654SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003655 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003656 wp<IBinder> dpy;
3657 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3658 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3659 dpy = mDisplays.keyAt(i);
3660 break;
3661 }
3662 }
3663 if (dpy == NULL) {
3664 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3665 // Just use the primary display so we have something to return
3666 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3667 }
3668 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003669}
3670
Keun young Park63f165f2012-08-31 10:53:36 -07003671bool SurfaceFlinger::startDdmConnection()
3672{
3673 void* libddmconnection_dso =
3674 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3675 if (!libddmconnection_dso) {
3676 return false;
3677 }
3678 void (*DdmConnection_start)(const char* name);
3679 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003680 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003681 if (!DdmConnection_start) {
3682 dlclose(libddmconnection_dso);
3683 return false;
3684 }
3685 (*DdmConnection_start)(getServiceName());
3686 return true;
3687}
3688
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003689status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003690 switch (code) {
3691 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003692 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003693 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003694 case CLEAR_ANIMATION_FRAME_STATS:
3695 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003697 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003698 {
3699 // codes that require permission check
3700 IPCThreadState* ipc = IPCThreadState::self();
3701 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003702 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003703 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003704 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003705 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003706 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003708 break;
3709 }
Robert Carr1db73f62016-12-21 12:58:51 -08003710 /*
3711 * Calling setTransactionState is safe, because you need to have been
3712 * granted a reference to Client* and Handle* to do anything with it.
3713 *
3714 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3715 */
3716 case SET_TRANSACTION_STATE:
3717 case CREATE_SCOPED_CONNECTION:
3718 {
3719 return OK;
3720 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003721 case CAPTURE_SCREEN:
3722 {
3723 // codes that require permission check
3724 IPCThreadState* ipc = IPCThreadState::self();
3725 const int pid = ipc->getCallingPid();
3726 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003727 if ((uid != AID_GRAPHICS) &&
3728 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003729 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003730 return PERMISSION_DENIED;
3731 }
3732 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733 }
3734 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003735 return OK;
3736}
3737
3738status_t SurfaceFlinger::onTransact(
3739 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3740{
3741 status_t credentialCheck = CheckTransactCodeCredentials(code);
3742 if (credentialCheck != OK) {
3743 return credentialCheck;
3744 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003745
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003746 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3747 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003748 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003749 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003750 IPCThreadState* ipc = IPCThreadState::self();
3751 const int pid = ipc->getCallingPid();
3752 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003753 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003754 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 return PERMISSION_DENIED;
3756 }
3757 int n;
3758 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003759 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003760 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003761 return NO_ERROR;
3762 case 1002: // SHOW_UPDATES
3763 n = data.readInt32();
3764 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003765 invalidateHwcGeometry();
3766 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003767 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003769 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003770 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003771 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003772 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773 setTransactionFlags(
3774 eTransactionNeeded|
3775 eDisplayTransactionNeeded|
3776 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003777 return NO_ERROR;
3778 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003779 case 1006:{ // send empty update
3780 signalRefresh();
3781 return NO_ERROR;
3782 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003783 case 1008: // toggle use of hw composer
3784 n = data.readInt32();
3785 mDebugDisableHWC = n ? 1 : 0;
3786 invalidateHwcGeometry();
3787 repaintEverything();
3788 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003789 case 1009: // toggle use of transform hint
3790 n = data.readInt32();
3791 mDebugDisableTransformHint = n ? 1 : 0;
3792 invalidateHwcGeometry();
3793 repaintEverything();
3794 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003795 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003796 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003797 reply->writeInt32(0);
3798 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003799 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003800 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 return NO_ERROR;
3802 case 1013: {
3803 Mutex::Autolock _l(mStateLock);
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003804 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003805 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003806 return NO_ERROR;
3807 }
3808 case 1014: {
3809 // daltonize
3810 n = data.readInt32();
3811 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003812 case 1:
3813 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3814 break;
3815 case 2:
3816 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3817 break;
3818 case 3:
3819 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3820 break;
3821 default:
3822 mDaltonizer.setType(ColorBlindnessType::None);
3823 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003824 }
3825 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003826 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003827 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003828 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003829 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003830 invalidateHwcGeometry();
3831 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003832 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003834 case 1015: {
3835 // apply a color matrix
3836 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003837 if (n) {
3838 // color matrix is sent as mat3 matrix followed by vec3
3839 // offset, then packed into a mat4 where the last row is
3840 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003841 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003842 for (size_t j = 0; j < 4; j++) {
3843 mColorMatrix[i][j] = data.readFloat();
3844 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003845 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003846 } else {
3847 mColorMatrix = mat4();
3848 }
3849 invalidateHwcGeometry();
3850 repaintEverything();
3851 return NO_ERROR;
3852 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003853 // This is an experimental interface
3854 // Needs to be shifted to proper binder interface when we productize
3855 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003856 n = data.readInt32();
3857 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003858 return NO_ERROR;
3859 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003860 case 1017: {
3861 n = data.readInt32();
3862 mForceFullDamage = static_cast<bool>(n);
3863 return NO_ERROR;
3864 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003865 case 1018: { // Modify Choreographer's phase offset
3866 n = data.readInt32();
3867 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3868 return NO_ERROR;
3869 }
3870 case 1019: { // Modify SurfaceFlinger's phase offset
3871 n = data.readInt32();
3872 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3873 return NO_ERROR;
3874 }
Irvel468051e2016-06-13 16:44:44 -07003875 case 1020: { // Layer updates interceptor
3876 n = data.readInt32();
3877 if (n) {
3878 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003879 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003880 }
3881 else{
3882 ALOGV("Interceptor disabled");
3883 mInterceptor.disable();
3884 }
3885 return NO_ERROR;
3886 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003887 case 1021: { // Disable HWC virtual displays
3888 n = data.readInt32();
3889 mUseHwcVirtualDisplays = !n;
3890 return NO_ERROR;
3891 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 }
3893 }
3894 return err;
3895}
3896
Mathias Agopian53331da2011-08-22 21:44:41 -07003897void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003898 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003899 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003900}
3901
Mathias Agopian59119e62010-10-11 12:37:43 -07003902// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003904// ---------------------------------------------------------------------------
3905
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003906/* The code below is here to handle b/8734824
3907 *
3908 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003909 * from the surfaceflinger thread to the calling binder thread, where they
3910 * are executed. This allows the calling thread in the calling process to be
3911 * reused and not depend on having "enough" binder threads to handle the
3912 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003913 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003914class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003915 /* Parts of GraphicProducerWrapper are run on two different threads,
3916 * communicating by sending messages via Looper but also by shared member
3917 * data. Coherence maintenance is subtle and in places implicit (ugh).
3918 *
3919 * Don't rely on Looper's sendMessage/handleMessage providing
3920 * release/acquire semantics for any data not actually in the Message.
3921 * Data going from surfaceflinger to binder threads needs to be
3922 * synchronized explicitly.
3923 *
3924 * Barrier open/wait do provide release/acquire semantics. This provides
3925 * implicit synchronization for data coming back from binder to
3926 * surfaceflinger threads.
3927 */
3928
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003929 sp<IGraphicBufferProducer> impl;
3930 sp<Looper> looper;
3931 status_t result;
3932 bool exitPending;
3933 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003934 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003935 uint32_t code;
3936 Parcel const* data;
3937 Parcel* reply;
3938
3939 enum {
3940 MSG_API_CALL,
3941 MSG_EXIT
3942 };
3943
3944 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003945 * Called on surfaceflinger thread. This is called by our "fake"
3946 * BpGraphicBufferProducer. We package the data and reply Parcel and
3947 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003948 */
3949 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003950 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003951 this->code = code;
3952 this->data = &data;
3953 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003955 // if we've exited, we run the message synchronously right here.
3956 // note (JH): as far as I can tell from looking at the code, this
3957 // never actually happens. if it does, i'm not sure if it happens
3958 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003959 handleMessage(Message(MSG_API_CALL));
3960 } else {
3961 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003962 // Prevent stores to this->{code, data, reply} from being
3963 // reordered later than the construction of Message.
3964 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003965 looper->sendMessage(this, Message(MSG_API_CALL));
3966 barrier.wait();
3967 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003968 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003969 }
3970
3971 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003972 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003973 * call the real BpGraphicBufferProducer.
3974 */
3975 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003976 int what = message.what;
3977 // Prevent reads below from happening before the read from Message
3978 atomic_thread_fence(memory_order_acquire);
3979 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003980 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003981 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003982 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003983 exitRequested = true;
3984 }
3985 }
3986
3987public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003988 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003989 : impl(impl),
3990 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003991 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003992 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003993 exitRequested(false),
3994 code(0),
3995 data(NULL),
3996 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003997 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003998
Jesse Hallb154c422014-07-13 12:47:02 -07003999 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004000 status_t waitForResponse() {
4001 do {
4002 looper->pollOnce(-1);
4003 } while (!exitRequested);
4004 return result;
4005 }
4006
Jesse Hallb154c422014-07-13 12:47:02 -07004007 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004008 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004009 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004010 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004011 // Ensure this->result is visible to the binder thread before it
4012 // handles the message.
4013 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004014 looper->sendMessage(this, Message(MSG_EXIT));
4015 }
4016};
4017
4018
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004019status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4020 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004021 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004022 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004023 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004024
4025 if (CC_UNLIKELY(display == 0))
4026 return BAD_VALUE;
4027
4028 if (CC_UNLIKELY(producer == 0))
4029 return BAD_VALUE;
4030
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004031 // if we have secure windows on this display, never allow the screen capture
4032 // unless the producer interface is local (i.e.: we can take a screenshot for
4033 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004034 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004035
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004036 // Convert to surfaceflinger's internal rotation type.
4037 Transform::orientation_flags rotationFlags;
4038 switch (rotation) {
4039 case ISurfaceComposer::eRotateNone:
4040 rotationFlags = Transform::ROT_0;
4041 break;
4042 case ISurfaceComposer::eRotate90:
4043 rotationFlags = Transform::ROT_90;
4044 break;
4045 case ISurfaceComposer::eRotate180:
4046 rotationFlags = Transform::ROT_180;
4047 break;
4048 case ISurfaceComposer::eRotate270:
4049 rotationFlags = Transform::ROT_270;
4050 break;
4051 default:
4052 rotationFlags = Transform::ROT_0;
4053 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4054 break;
4055 }
4056
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004057 class MessageCaptureScreen : public MessageBase {
4058 SurfaceFlinger* flinger;
4059 sp<IBinder> display;
4060 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004061 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004062 uint32_t reqWidth, reqHeight;
4063 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004064 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004065 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004066 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004067 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004068 public:
4069 MessageCaptureScreen(SurfaceFlinger* flinger,
4070 const sp<IBinder>& display,
4071 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004072 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004073 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004074 bool useIdentityTransform,
4075 Transform::orientation_flags rotation,
4076 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004077 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004078 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004079 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004080 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004081 rotation(rotation), result(PERMISSION_DENIED),
4082 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004083 {
4084 }
4085 status_t getResult() const {
4086 return result;
4087 }
4088 virtual bool handler() {
4089 Mutex::Autolock _l(flinger->mStateLock);
4090 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08004091 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004092 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004093 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004094 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004095 return true;
4096 }
4097 };
4098
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004099 // this creates a "fake" BBinder which will serve as a "fake" remote
4100 // binder to receive the marshaled calls and forward them to the
4101 // real remote (a BpGraphicBufferProducer)
4102 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4103
4104 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4105 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004106 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004107 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004108 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004109 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004110
4111 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004112 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004113 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004114 }
4115 return res;
4116}
4117
Mathias Agopian180f10d2013-04-10 22:55:41 -07004118
4119void SurfaceFlinger::renderScreenImplLocked(
4120 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004121 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004122 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004123 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004124{
4125 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004126 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004127
4128 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004129 const int32_t hw_w = hw->getWidth();
4130 const int32_t hw_h = hw->getHeight();
4131 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004132 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004133
Dan Stozac1879002014-05-22 15:59:05 -07004134 // if a default or invalid sourceCrop is passed in, set reasonable values
4135 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4136 !sourceCrop.isValid()) {
4137 sourceCrop.setLeftTop(Point(0, 0));
4138 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4139 }
4140
4141 // ensure that sourceCrop is inside screen
4142 if (sourceCrop.left < 0) {
4143 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4144 }
Dan Stozabe31f442014-06-11 11:20:54 -07004145 if (sourceCrop.right > hw_w) {
4146 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004147 }
4148 if (sourceCrop.top < 0) {
4149 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4150 }
Dan Stozabe31f442014-06-11 11:20:54 -07004151 if (sourceCrop.bottom > hw_h) {
4152 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004153 }
4154
Mathias Agopian180f10d2013-04-10 22:55:41 -07004155 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004156 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004157
4158 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004159 engine.setViewportAndProjection(
4160 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004161 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004162
4163 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004164 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004165
Robert Carr1f0a16a2016-10-24 16:27:39 -07004166 // We loop through the first level of layers without traversing,
4167 // as we need to interpret min/max layer Z in the top level Z space.
4168 for (const auto& layer : mDrawingState.layersSortedByZ) {
4169 if (layer->getLayerStack() != hw->getLayerStack()) {
4170 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004171 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004172 const Layer::State& state(layer->getDrawingState());
4173 if (state.z < minLayerZ || state.z > maxLayerZ) {
4174 continue;
4175 }
4176 layer->traverseInZOrder([&](Layer* layer) {
4177 if (!layer->isVisible()) {
4178 return;
4179 }
4180 if (filtering) layer->setFiltering(true);
4181 layer->draw(hw, useIdentityTransform);
4182 if (filtering) layer->setFiltering(false);
4183 });
4184 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004185
Mathias Agopian931bda12013-08-28 18:11:46 -07004186 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004187}
4188
4189
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004190status_t SurfaceFlinger::captureScreenImplLocked(
4191 const sp<const DisplayDevice>& hw,
4192 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004193 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004194 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004195 bool useIdentityTransform, Transform::orientation_flags rotation,
4196 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004197{
4198 ATRACE_CALL();
4199
Mathias Agopian180f10d2013-04-10 22:55:41 -07004200 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004201 uint32_t hw_w = hw->getWidth();
4202 uint32_t hw_h = hw->getHeight();
4203
4204 if (rotation & Transform::ROT_90) {
4205 std::swap(hw_w, hw_h);
4206 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004207
Mathias Agopian180f10d2013-04-10 22:55:41 -07004208 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4209 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4210 reqWidth, reqHeight, hw_w, hw_h);
4211 return BAD_VALUE;
4212 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004213
Mathias Agopian180f10d2013-04-10 22:55:41 -07004214 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4215 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4216
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004217 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004218 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004219 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004220 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4221 (state.z < minLayerZ || state.z > maxLayerZ)) {
4222 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004223 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004224 layer->traverseInZOrder([&](Layer *layer) {
4225 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4226 layer->isSecure());
4227 });
4228 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004229
4230 if (!isLocalScreenshot && secureLayerIsVisible) {
4231 ALOGW("FB is protected: PERMISSION_DENIED");
4232 return PERMISSION_DENIED;
4233 }
4234
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004235 // create a surface (because we're a producer, and we need to
4236 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004237 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004238
4239 // Put the screenshot Surface into async mode so that
4240 // Layer::headFenceHasSignaled will always return true and we'll latch the
4241 // first buffer regardless of whether or not its acquire fence has
4242 // signaled. This is needed to avoid a race condition in the rotation
4243 // animation. See b/30209608
4244 sur->setAsyncMode(true);
4245
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004246 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004247
Michael Lentine5a16a622015-05-21 13:48:24 -07004248 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4249 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004250 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4251 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004252
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004253 int err = 0;
4254 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004255 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004256 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4257 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004258
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004259 if (err == NO_ERROR) {
4260 ANativeWindowBuffer* buffer;
4261 /* TODO: Once we have the sync framework everywhere this can use
4262 * server-side waits on the fence that dequeueBuffer returns.
4263 */
4264 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4265 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004266 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004267 // create an EGLImage from the buffer so we can later
4268 // turn it into a texture
4269 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4270 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4271 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004272 // this binds the given EGLImage as a framebuffer for the
4273 // duration of this scope.
4274 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4275 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004276 // this will in fact render into our dequeued buffer
4277 // via an FBO, which means we didn't have to create
4278 // an EGLSurface and therefore we're not
4279 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004280 renderScreenImplLocked(
4281 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4282 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004283
Riley Andrews86639902014-08-15 12:27:24 -07004284 // Attempt to create a sync khr object that can produce a sync point. If that
4285 // isn't available, create a non-dupable sync object in the fallback path and
4286 // wait on it directly.
4287 EGLSyncKHR sync;
4288 if (!DEBUG_SCREENSHOTS) {
4289 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004290 // native fence fd will not be populated until flush() is done.
4291 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004292 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004293 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004294 }
Riley Andrews86639902014-08-15 12:27:24 -07004295 if (sync != EGL_NO_SYNC_KHR) {
4296 // get the sync fd
4297 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4298 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4299 ALOGW("captureScreen: failed to dup sync khr object");
4300 syncFd = -1;
4301 }
4302 eglDestroySyncKHR(mEGLDisplay, sync);
4303 } else {
4304 // fallback path
4305 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4306 if (sync != EGL_NO_SYNC_KHR) {
4307 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4308 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4309 EGLint eglErr = eglGetError();
4310 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4311 ALOGW("captureScreen: fence wait timed out");
4312 } else {
4313 ALOGW_IF(eglErr != EGL_SUCCESS,
4314 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4315 }
4316 eglDestroySyncKHR(mEGLDisplay, sync);
4317 } else {
4318 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4319 }
4320 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004321 if (DEBUG_SCREENSHOTS) {
4322 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4323 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4324 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4325 hw, minLayerZ, maxLayerZ);
4326 delete [] pixels;
4327 }
4328
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004329 } else {
4330 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4331 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004332 window->cancelBuffer(window, buffer, syncFd);
4333 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004334 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004335 // destroy our image
4336 eglDestroyImageKHR(mEGLDisplay, image);
4337 } else {
4338 result = BAD_VALUE;
4339 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004340 if (buffer) {
4341 // queueBuffer takes ownership of syncFd
4342 result = window->queueBuffer(window, buffer, syncFd);
4343 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004344 }
4345 } else {
4346 result = BAD_VALUE;
4347 }
4348 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4349 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004350
Mathias Agopian74c40c02010-09-29 13:02:36 -07004351 return result;
4352}
4353
Mathias Agopiand5556842013-09-19 17:08:37 -07004354void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004355 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004356 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004357 for (size_t y=0 ; y<h ; y++) {
4358 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4359 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004360 if (p[x] != 0xFF000000) return;
4361 }
4362 }
4363 ALOGE("*** we just took a black screenshot ***\n"
4364 "requested minz=%d, maxz=%d, layerStack=%d",
4365 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004366
Robert Carr2047fae2016-11-28 14:09:09 -08004367 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004368 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004369 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004370 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4371 state.z <= maxLayerZ) {
4372 layer->traverseInZOrder([&](Layer* layer) {
4373 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4374 layer->isVisible() ? '+' : '-',
4375 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004376 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004377 i++;
4378 });
4379 }
4380 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004381 }
4382}
4383
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004384// ---------------------------------------------------------------------------
4385
Robert Carr2047fae2016-11-28 14:09:09 -08004386void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4387 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004388}
4389
Robert Carr2047fae2016-11-28 14:09:09 -08004390void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4391 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004392}
4393
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004394}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004395
4396
4397#if defined(__gl_h_)
4398#error "don't include gl/gl.h in this file"
4399#endif
4400
4401#if defined(__gl2_h_)
4402#error "don't include gl2/gl2.h in this file"
4403#endif