blob: d72b3b5a35b3ba823f16e55dd26c337e6120a5cf [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Romain Guyf8b4ca52017-03-16 18:39:20 +000048#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800121bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800122int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600123bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700126 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700128 mTransactionPending(false),
129 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700131 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700132 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800133 mHwc(nullptr),
134 mRealHwc(nullptr),
135 mVrHwc(nullptr),
136 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800152 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000153 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700154 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700155 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700160 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 mNumLayers(0),
162 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
Steven Thomas050b2c82017-03-06 11:45:16 -0800187 // Vr flinger is only enabled on Daydream ready devices.
188 useVrFlinger = getBool< ISurfaceFlingerConfigs,
189 &ISurfaceFlingerConfigs::useVrFlinger>(false);
190
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
192 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
193
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600194 hasWideColorDisplay =
195 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 // debugging stuff...
198 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700201 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showupdates", value, "0");
204 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 property_get("debug.sf.ddms", value, "0");
207 mDebugDDMS = atoi(value);
208 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700209 if (!startDdmConnection()) {
210 // start failed, and DDMS debugging not enabled
211 mDebugDDMS = 0;
212 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700213 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700214 ALOGI_IF(mDebugRegion, "showupdates enabled");
215 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700216
217 property_get("debug.sf.disable_backpressure", value, "0");
218 mPropagateBackpressure = !atoi(value);
219 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700220
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800221 property_get("debug.sf.enable_hwc_vds", value, "0");
222 mUseHwcVirtualDisplays = atoi(value);
223 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800225 property_get("ro.sf.disable_triple_buffer", value, "1");
226 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230void SurfaceFlinger::onFirstRef()
231{
232 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235SurfaceFlinger::~SurfaceFlinger()
236{
Mathias Agopiana4912602012-07-12 14:25:33 -0700237 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
238 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
239 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
Romain Guyf8b4ca52017-03-16 18:39:20 +0000343sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
344{
345 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
346 return gba;
347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
574 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800575 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800576 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
578
Jesse Hall692c7232012-11-08 15:41:56 -0800579 Mutex::Autolock _l(mStateLock);
580
Steven Thomas050b2c82017-03-06 11:45:16 -0800581 if (useVrFlinger) {
582 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
583 mVrFlingerRequestsDisplay = requestDisplay;
584 signalTransaction();
585 };
586 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
587 vrFlingerRequestDisplayCallback);
588 if (!mVrFlinger) {
589 ALOGE("Failed to start vrflinger");
590 }
591 }
592
Mathias Agopian875d8e12013-06-07 15:35:48 -0700593 // retrieve the EGL context that was selected/created
594 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700595
Mathias Agopianda27af92012-09-13 18:17:13 -0700596 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
597 "couldn't create EGLContext");
598
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 // make the GLContext current so that we can create textures when creating
600 // Layers (which may happens before we render something)
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700601 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700602
Jamie Gennisd1700752013-10-14 12:22:52 -0700603 mEventControlThread = new EventControlThread(this);
604 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
605
Mathias Agopian92a979a2012-08-02 18:32:23 -0700606 // initialize our drawing state
607 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700608
Andy McFadden13a082e2012-08-24 10:16:42 -0700609 // set initial conditions (e.g. unblank default device)
610 initializeDisplays();
611
Dan Stoza4e637772016-07-28 13:31:51 -0700612 mRenderEngine->primeCache();
613
Wei Wangb254fa32017-01-31 17:43:23 -0800614 mStartBootAnimThread = new StartBootAnimThread();
615 if (mStartBootAnimThread->Start() != NO_ERROR) {
616 ALOGE("Run StartBootAnimThread failed!");
617 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800618
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700620}
621
Mathias Agopiana67e4182012-06-19 17:26:12 -0700622void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800623 // Start boot animation service by setting a property mailbox
624 // if property setting thread is already running, Start() will be just a NOP
625 mStartBootAnimThread->Start();
626 // Wait until property was set
627 if (mStartBootAnimThread->join() != NO_ERROR) {
628 ALOGE("Join StartBootAnimThread failed!");
629 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700630}
631
Mathias Agopian875d8e12013-06-07 15:35:48 -0700632size_t SurfaceFlinger::getMaxTextureSize() const {
633 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700634}
635
Mathias Agopian875d8e12013-06-07 15:35:48 -0700636size_t SurfaceFlinger::getMaxViewportDims() const {
637 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700638}
639
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800641
Jamie Gennis582270d2011-08-17 18:19:00 -0700642bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800643 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800644 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800645 return authenticateSurfaceTextureLocked(bufferProducer);
646}
647
648bool SurfaceFlinger::authenticateSurfaceTextureLocked(
649 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800650 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700651 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800652}
653
Brian Anderson6b376712017-04-04 10:51:39 -0700654status_t SurfaceFlinger::getSupportedFrameTimestamps(
655 std::vector<FrameEvent>* outSupported) const {
656 *outSupported = {
657 FrameEvent::REQUESTED_PRESENT,
658 FrameEvent::ACQUIRE,
659 FrameEvent::LATCH,
660 FrameEvent::FIRST_REFRESH_START,
661 FrameEvent::LAST_REFRESH_START,
662 FrameEvent::GPU_COMPOSITION_DONE,
663 FrameEvent::DEQUEUE_READY,
664 FrameEvent::RELEASE,
665 };
666 if (!getHwComposer().hasCapability(
667 HWC2::Capability::PresentFenceIsNotReliable)) {
668 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
669 }
670 return NO_ERROR;
671}
672
Dan Stoza7f7da322014-05-02 15:26:25 -0700673status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
674 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700675 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700676 return BAD_VALUE;
677 }
678
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500679 if (!display.get())
680 return NAME_NOT_FOUND;
681
Jesse Hall692c7232012-11-08 15:41:56 -0800682 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700683 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800684 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700685 type = i;
686 break;
687 }
688 }
689
690 if (type < 0) {
691 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700692 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700693
Mathias Agopian8b736f12012-08-13 17:54:26 -0700694 // TODO: Not sure if display density should handled by SF any longer
695 class Density {
696 static int getDensityFromProperty(char const* propName) {
697 char property[PROPERTY_VALUE_MAX];
698 int density = 0;
699 if (property_get(propName, property, NULL) > 0) {
700 density = atoi(property);
701 }
702 return density;
703 }
704 public:
705 static int getEmuDensity() {
706 return getDensityFromProperty("qemu.sf.lcd_density"); }
707 static int getBuildDensity() {
708 return getDensityFromProperty("ro.sf.lcd_density"); }
709 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700710
Dan Stoza7f7da322014-05-02 15:26:25 -0700711 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700712
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700714 DisplayInfo info = DisplayInfo();
715
Dan Stoza9e56aa02015-11-02 13:00:03 -0800716 float xdpi = hwConfig->getDpiX();
717 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700718
719 if (type == DisplayDevice::DISPLAY_PRIMARY) {
720 // The density of the device is provided by a build property
721 float density = Density::getBuildDensity() / 160.0f;
722 if (density == 0) {
723 // the build doesn't provide a density -- this is wrong!
724 // use xdpi instead
725 ALOGE("ro.sf.lcd_density must be defined as a build property");
726 density = xdpi / 160.0f;
727 }
728 if (Density::getEmuDensity()) {
729 // if "qemu.sf.lcd_density" is specified, it overrides everything
730 xdpi = ydpi = density = Density::getEmuDensity();
731 density /= 160.0f;
732 }
733 info.density = density;
734
735 // TODO: this needs to go away (currently needed only by webkit)
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700736 {
737 Mutex::Autolock _l(mStateLock);
738 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
739 info.orientation = hw->getOrientation();
740 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700741 } else {
742 // TODO: where should this value come from?
743 static const int TV_DENSITY = 213;
744 info.density = TV_DENSITY / 160.0f;
745 info.orientation = 0;
746 }
747
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748 info.w = hwConfig->getWidth();
749 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 info.xdpi = xdpi;
751 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900753 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754
Andy McFadden91b2ca82014-06-13 14:04:23 -0700755 // This is how far in advance a buffer must be queued for
756 // presentation at a given time. If you want a buffer to appear
757 // on the screen at time N, you must submit the buffer before
758 // (N - presentationDeadline).
759 //
760 // Normally it's one full refresh period (to give SF a chance to
761 // latch the buffer), but this can be reduced by configuring a
762 // DispSync offset. Any additional delays introduced by the hardware
763 // composer or panel must be accounted for here.
764 //
765 // We add an additional 1ms to allow for processing time and
766 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800768 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700769
770 // All non-virtual displays are currently considered secure.
771 info.secure = true;
772
Michael Wright28f24d02016-07-12 13:30:53 -0700773 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700774 }
775
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 return NO_ERROR;
777}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700778
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800779status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700780 DisplayStatInfo* stats) {
781 if (stats == NULL) {
782 return BAD_VALUE;
783 }
784
785 // FIXME for now we always return stats for the primary display
786 memset(stats, 0, sizeof(*stats));
787 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
788 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
789 return NO_ERROR;
790}
791
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700792int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800793 if (display == NULL) {
794 ALOGE("%s : display is NULL", __func__);
795 return BAD_VALUE;
796 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700797
798 Mutex::Autolock _l(mStateLock);
Dan Stoza24a42e92015-03-09 10:04:11 -0700799 sp<DisplayDevice> device(getDisplayDevice(display));
800 if (device != NULL) {
801 return device->getActiveConfig();
802 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700803
Dan Stoza24a42e92015-03-09 10:04:11 -0700804 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700805}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700806
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700807void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
808 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
809 this);
810 int32_t type = hw->getDisplayType();
811 int currentMode = hw->getActiveConfig();
812
813 if (mode == currentMode) {
814 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
815 return;
816 }
817
818 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
819 ALOGW("Trying to set config for virtual display");
820 return;
821 }
822
823 hw->setActiveConfig(mode);
824 getHwComposer().setActiveConfig(type, mode);
825}
826
827status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
828 class MessageSetActiveConfig: public MessageBase {
829 SurfaceFlinger& mFlinger;
830 sp<IBinder> mDisplay;
831 int mMode;
832 public:
833 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
834 int mode) :
835 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
836 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700837 Vector<DisplayInfo> configs;
838 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700839 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700840 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700841 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700842 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700843 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700844 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
845 if (hw == NULL) {
846 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700847 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700848 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
849 ALOGW("Attempt to set active config = %d for virtual display",
850 mMode);
851 } else {
852 mFlinger.setActiveConfigInternal(hw, mMode);
853 }
854 return true;
855 }
856 };
857 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
858 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700859 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700860}
Michael Wright28f24d02016-07-12 13:30:53 -0700861status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
862 Vector<android_color_mode_t>* outColorModes) {
863 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
864 return BAD_VALUE;
865 }
866
867 if (!display.get()) {
868 return NAME_NOT_FOUND;
869 }
870
871 int32_t type = NAME_NOT_FOUND;
872 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
873 if (display == mBuiltinDisplays[i]) {
874 type = i;
875 break;
876 }
877 }
878
879 if (type < 0) {
880 return type;
881 }
882
883 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
884 outColorModes->clear();
885 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
886
887 return NO_ERROR;
888}
889
890android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700891 Mutex::Autolock _l(mStateLock);
Michael Wright28f24d02016-07-12 13:30:53 -0700892 sp<DisplayDevice> device(getDisplayDevice(display));
893 if (device != nullptr) {
894 return device->getActiveColorMode();
895 }
896 return static_cast<android_color_mode_t>(BAD_VALUE);
897}
898
899void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
900 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700901 int32_t type = hw->getDisplayType();
902 android_color_mode_t currentMode = hw->getActiveColorMode();
903
904 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700905 return;
906 }
907
908 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
909 ALOGW("Trying to set config for virtual display");
910 return;
911 }
912
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600913 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
914 hw->getDisplayType());
915
Michael Wright28f24d02016-07-12 13:30:53 -0700916 hw->setActiveColorMode(mode);
917 getHwComposer().setActiveColorMode(type, mode);
918}
919
920
921status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
922 android_color_mode_t colorMode) {
923 class MessageSetActiveColorMode: public MessageBase {
924 SurfaceFlinger& mFlinger;
925 sp<IBinder> mDisplay;
926 android_color_mode_t mMode;
927 public:
928 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
929 android_color_mode_t mode) :
930 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
931 virtual bool handler() {
932 Vector<android_color_mode_t> modes;
933 mFlinger.getDisplayColorModes(mDisplay, &modes);
934 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
935 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600936 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
937 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700938 return true;
939 }
940 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
941 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600942 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
943 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700944 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600945 ALOGW("Attempt to set active color mode %s %d for virtual display",
946 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700947 } else {
948 mFlinger.setActiveColorModeInternal(hw, mMode);
949 }
950 return true;
951 }
952 };
953 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
954 postMessageSync(msg);
955 return NO_ERROR;
956}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700957
Svetoslavd85084b2014-03-20 10:28:31 -0700958status_t SurfaceFlinger::clearAnimationFrameStats() {
959 Mutex::Autolock _l(mStateLock);
960 mAnimFrameTracker.clearStats();
961 return NO_ERROR;
962}
963
964status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
965 Mutex::Autolock _l(mStateLock);
966 mAnimFrameTracker.getStats(outStats);
967 return NO_ERROR;
968}
969
Dan Stozac4f471e2016-03-24 09:31:08 -0700970status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
971 HdrCapabilities* outCapabilities) const {
972 Mutex::Autolock _l(mStateLock);
973
974 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
975 if (displayDevice == nullptr) {
976 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
977 return BAD_VALUE;
978 }
979
980 std::unique_ptr<HdrCapabilities> capabilities =
981 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
982 if (capabilities) {
983 std::swap(*outCapabilities, *capabilities);
984 } else {
985 return BAD_VALUE;
986 }
987
988 return NO_ERROR;
989}
990
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700991status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
992 if (enable == mInjectVSyncs) {
993 return NO_ERROR;
994 }
995
996 if (enable) {
997 mInjectVSyncs = enable;
998 ALOGV("VSync Injections enabled");
999 if (mVSyncInjector.get() == nullptr) {
1000 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001001 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001002 }
1003 mEventQueue.setEventThread(mInjectorEventThread);
1004 } else {
1005 mInjectVSyncs = enable;
1006 ALOGV("VSync Injections disabled");
1007 mEventQueue.setEventThread(mSFEventThread);
1008 mVSyncInjector.clear();
1009 }
1010 return NO_ERROR;
1011}
1012
1013status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1014 if (!mInjectVSyncs) {
1015 ALOGE("VSync Injections not enabled");
1016 return BAD_VALUE;
1017 }
1018 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1019 ALOGV("Injecting VSync inside SurfaceFlinger");
1020 mVSyncInjector->onInjectSyncEvent(when);
1021 }
1022 return NO_ERROR;
1023}
1024
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001025// ----------------------------------------------------------------------------
1026
1027sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001028 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001029}
1030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001031// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001032
1033void SurfaceFlinger::waitForEvent() {
1034 mEventQueue.waitMessage();
1035}
1036
1037void SurfaceFlinger::signalTransaction() {
1038 mEventQueue.invalidate();
1039}
1040
1041void SurfaceFlinger::signalLayerUpdate() {
1042 mEventQueue.invalidate();
1043}
1044
1045void SurfaceFlinger::signalRefresh() {
1046 mEventQueue.refresh();
1047}
1048
1049status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001050 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001051 return mEventQueue.postMessage(msg, reltime);
1052}
1053
1054status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001055 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001056 status_t res = mEventQueue.postMessage(msg, reltime);
1057 if (res == NO_ERROR) {
1058 msg->wait();
1059 }
1060 return res;
1061}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001062
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001063void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001064 do {
1065 waitForEvent();
1066 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001067}
1068
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001069void SurfaceFlinger::enableHardwareVsync() {
1070 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001071 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001072 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001073 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1074 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001075 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001076 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077}
1078
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 Mutex::Autolock _l(mHWVsyncLock);
1081
Jesse Hall948fe0c2013-10-14 12:56:09 -07001082 if (makeAvailable) {
1083 mHWVsyncAvailable = true;
1084 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001085 // Hardware vsync is not currently available, so abort the resync
1086 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087 return;
1088 }
1089
Dan Stoza9e56aa02015-11-02 13:00:03 -08001090 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1091 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092
1093 mPrimaryDispSync.reset();
1094 mPrimaryDispSync.setPeriod(period);
1095
1096 if (!mPrimaryHWVsyncEnabled) {
1097 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001098 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1099 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100 mPrimaryHWVsyncEnabled = true;
1101 }
1102}
1103
Jesse Hall948fe0c2013-10-14 12:56:09 -07001104void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105 Mutex::Autolock _l(mHWVsyncLock);
1106 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001107 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1108 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001109 mPrimaryDispSync.endResync();
1110 mPrimaryHWVsyncEnabled = false;
1111 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001112 if (makeUnavailable) {
1113 mHWVsyncAvailable = false;
1114 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115}
1116
Tim Murray4a4e4a22016-04-19 16:29:23 +00001117void SurfaceFlinger::resyncWithRateLimit() {
1118 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1119 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001120 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001121 }
1122}
1123
Steven Thomas3cfac282017-02-06 12:29:30 -08001124void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1125 nsecs_t timestamp) {
1126 Mutex::Autolock lock(mStateLock);
1127 // Ignore any vsyncs from the non-active hardware composer.
1128 if (composer != mHwc) {
1129 return;
1130 }
1131
Jamie Gennisd1700752013-10-14 12:22:52 -07001132 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001133
Jamie Gennisd1700752013-10-14 12:22:52 -07001134 { // Scope for the lock
1135 Mutex::Autolock _l(mHWVsyncLock);
1136 if (type == 0 && mPrimaryHWVsyncEnabled) {
1137 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001138 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001139 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001140
1141 if (needsHwVsync) {
1142 enableHardwareVsync();
1143 } else {
1144 disableHardwareVsync(false);
1145 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001146}
1147
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001148void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001149 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001150 *compositorTiming = mCompositorTiming;
1151}
1152
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001153void SurfaceFlinger::createDefaultDisplayDevice() {
1154 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1155 wp<IBinder> token = mBuiltinDisplays[type];
1156
1157 // All non-virtual displays are currently considered secure.
1158 const bool isSecure = true;
1159
1160 sp<IGraphicBufferProducer> producer;
1161 sp<IGraphicBufferConsumer> consumer;
1162 BufferQueue::createBufferQueue(&producer, &consumer, new GraphicBufferAlloc());
1163
1164 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1165
1166 bool hasWideColorModes = false;
1167 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(
1168 type);
1169 for (android_color_mode_t colorMode : modes) {
1170 switch (colorMode) {
1171 case HAL_COLOR_MODE_DISPLAY_P3:
1172 case HAL_COLOR_MODE_ADOBE_RGB:
1173 case HAL_COLOR_MODE_DCI_P3:
1174 hasWideColorModes = true;
1175 break;
1176 default:
1177 break;
1178 }
1179 }
1180 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1181 token, fbs, producer, mRenderEngine->getEGLConfig(),
1182 hasWideColorModes && hasWideColorDisplay);
1183 mDisplays.add(token, hw);
1184 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1185 if (hasWideColorModes && hasWideColorDisplay) {
1186 defaultColorMode = HAL_COLOR_MODE_SRGB;
1187 }
1188 setActiveColorModeInternal(hw, defaultColorMode);
1189}
1190
1191void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001193
1194 if (composer->isUsingVrComposer()) {
1195 // We handle initializing the primary display device for the VR
1196 // window manager hwc explicitly at the time of transition.
1197 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1198 ALOGE("External displays are not supported by the vr hardware composer.");
1199 }
1200 return;
1201 }
1202
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1204 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001205 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1206 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 } else {
1208 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001209 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001210 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001212 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001213 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1214 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001215 }
1216 setTransactionFlags(eDisplayTransactionNeeded);
1217
Andy McFadden9e9689c2012-10-10 18:17:51 -07001218 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001219 }
Mathias Agopian86303202012-07-24 22:46:10 -07001220}
1221
Steven Thomas3cfac282017-02-06 12:29:30 -08001222void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1223 Mutex::Autolock lock(mStateLock);
1224 if (composer == mHwc) {
1225 repaintEverything();
1226 } else {
1227 // This isn't from our current hardware composer. If it's a callback
1228 // from the real composer, forward the refresh request to vr
1229 // flinger. Otherwise ignore it.
1230 if (!composer->isUsingVrComposer()) {
1231 mVrFlinger->OnHardwareComposerRefresh();
1232 }
1233 }
1234}
1235
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001237 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 getHwComposer().setVsyncEnabled(disp,
1239 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001240}
1241
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001242void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1243 for (size_t i = 0; i < layers.size(); ++i) {
1244 layers[i]->clearHwcLayers();
1245 }
1246}
1247
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001248// Note: it is assumed the caller holds |mStateLock| when this is called
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001249void SurfaceFlinger::resetHwc() {
1250 disableHardwareVsync(true);
1251 clearHwcLayers(mDrawingState.layersSortedByZ);
1252 clearHwcLayers(mCurrentState.layersSortedByZ);
1253 // Clear the drawing state so that the logic inside of
1254 // handleTransactionLocked will fire. It will determine the delta between
1255 // mCurrentState and mDrawingState and re-apply all changes when we make the
1256 // transition.
1257 mDrawingState.displays.clear();
1258 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001259 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001260}
1261
Steven Thomas050b2c82017-03-06 11:45:16 -08001262void SurfaceFlinger::updateVrFlinger() {
1263 if (!mVrFlinger)
1264 return;
1265 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1266 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001267 return;
1268 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001269
1270 bool vrHwcNewlyInitialized = false;
1271
Steven Thomas050b2c82017-03-06 11:45:16 -08001272 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001273 // Construct new HWComposer without holding any locks.
1274 mVrHwc = new HWComposer(true);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001275 vrHwcNewlyInitialized = true;
Mark Urbanus209beca2017-02-23 11:16:04 -08001276 ALOGV("Vr HWC created");
1277 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001278
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001279 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001280
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001281 if (vrFlingerRequestsDisplay) {
1282 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001283
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001284 mHwc = mVrHwc;
1285 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001286
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001287 if (vrHwcNewlyInitialized) {
1288 mVrHwc->setEventHandler(
1289 static_cast<HWComposer::EventHandler*>(this));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001290 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001291 } else {
1292 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001293
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001294 resetHwc();
1295
1296 mHwc = mRealHwc;
1297 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001298 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001299
1300 mVisibleRegionsDirty = true;
1301 invalidateHwcGeometry();
1302
1303 // Explicitly re-initialize the primary display. This is because some other
1304 // parts of this class rely on the primary display always being available.
1305 createDefaultDisplayDevice();
1306
1307 android_atomic_or(1, &mRepaintEverything);
1308 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309}
1310
Mathias Agopian4fec8732012-06-29 14:12:52 -07001311void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001312 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001313 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001314 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001315 bool frameMissed = !mHadClientComposition &&
1316 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001317 (mPreviousPresentFence->getSignalTime() ==
1318 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001319 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001320 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001321 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001322 signalLayerUpdate();
1323 break;
1324 }
1325
Steven Thomas050b2c82017-03-06 11:45:16 -08001326 // Now that we're going to make it to the handleMessageTransaction()
1327 // call below it's safe to call updateVrFlinger(), which will
1328 // potentially trigger a display handoff.
1329 updateVrFlinger();
1330
Dan Stoza6b9454d2014-11-07 16:00:59 -08001331 bool refreshNeeded = handleMessageTransaction();
1332 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001333 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001334 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001335 // Signal a refresh if a transaction modified the window state,
1336 // a new buffer was latched, or if HWC has requested a full
1337 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001338 signalRefresh();
1339 }
1340 break;
1341 }
1342 case MessageQueue::REFRESH: {
1343 handleMessageRefresh();
1344 break;
1345 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001346 }
1347}
1348
Dan Stoza6b9454d2014-11-07 16:00:59 -08001349bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001350 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001351 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001352 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001353 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001354 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001355 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001356}
1357
Dan Stoza6b9454d2014-11-07 16:00:59 -08001358bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001359 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001360 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001361}
1362
1363void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001364 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001365
Pablo Ceballos40845df2016-01-25 17:41:15 -08001366 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001367
Brian Andersond6927fb2016-07-23 23:37:30 -07001368 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001369 rebuildLayerStacks();
1370 setUpHWComposer();
1371 doDebugFlashRegions();
1372 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001373 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001374
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001375 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001376
1377 mHadClientComposition = false;
1378 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1379 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1380 mHadClientComposition = mHadClientComposition ||
1381 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1382 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001383
Dan Stoza9e56aa02015-11-02 13:00:03 -08001384 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387void SurfaceFlinger::doDebugFlashRegions()
1388{
1389 // is debugging enabled
1390 if (CC_LIKELY(!mDebugRegion))
1391 return;
1392
1393 const bool repaintEverything = mRepaintEverything;
1394 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1395 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001396 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001397 // transform the dirty region into this screen's coordinate space
1398 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1399 if (!dirtyRegion.isEmpty()) {
1400 // redraw the whole screen
1401 doComposeSurfaces(hw, Region(hw->bounds()));
1402
1403 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001404 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001405 RenderEngine& engine(getRenderEngine());
1406 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1407
Mathias Agopianda27af92012-09-13 18:17:13 -07001408 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001409 }
1410 }
1411 }
1412
1413 postFramebuffer();
1414
1415 if (mDebugRegion > 1) {
1416 usleep(mDebugRegion * 1000);
1417 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001418
Dan Stoza9e56aa02015-11-02 13:00:03 -08001419 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001420 auto& displayDevice = mDisplays[displayId];
1421 if (!displayDevice->isDisplayOn()) {
1422 continue;
1423 }
1424
1425 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001426 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1427 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001428 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001429}
1430
Brian Andersond6927fb2016-07-23 23:37:30 -07001431void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001432{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 ATRACE_CALL();
1434 ALOGV("preComposition");
1435
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001437 mDrawingState.traverseInZOrder([&](Layer* layer) {
1438 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001439 needExtraInvalidate = true;
1440 }
Robert Carr2047fae2016-11-28 14:09:09 -08001441 });
1442
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 if (needExtraInvalidate) {
1444 signalLayerUpdate();
1445 }
1446}
1447
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001448void SurfaceFlinger::updateCompositorTiming(
1449 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1450 std::shared_ptr<FenceTime>& presentFenceTime) {
1451 // Update queue of past composite+present times and determine the
1452 // most recently known composite to present latency.
1453 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1454 nsecs_t compositeToPresentLatency = -1;
1455 while (!mCompositePresentTimes.empty()) {
1456 CompositePresentTime& cpt = mCompositePresentTimes.front();
1457 // Cached values should have been updated before calling this method,
1458 // which helps avoid duplicate syscalls.
1459 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1460 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1461 break;
1462 }
1463 compositeToPresentLatency = displayTime - cpt.composite;
1464 mCompositePresentTimes.pop();
1465 }
1466
1467 // Don't let mCompositePresentTimes grow unbounded, just in case.
1468 while (mCompositePresentTimes.size() > 16) {
1469 mCompositePresentTimes.pop();
1470 }
1471
Brian Andersond0010582017-03-07 13:20:31 -08001472 setCompositorTimingSnapped(
1473 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1474}
1475
1476void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1477 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001478 // Integer division and modulo round toward 0 not -inf, so we need to
1479 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001480 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1482 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1483
Brian Andersond0010582017-03-07 13:20:31 -08001484 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1485 if (idealLatency <= 0) {
1486 idealLatency = vsyncInterval;
1487 }
1488
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 // Snap the latency to a value that removes scheduling jitter from the
1490 // composition and present times, which often have >1ms of jitter.
1491 // Reducing jitter is important if an app attempts to extrapolate
1492 // something (such as user input) to an accurate diasplay time.
1493 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1494 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001495 nsecs_t bias = vsyncInterval / 2;
1496 int64_t extraVsyncs =
1497 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1498 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1499 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001500
Brian Andersond0010582017-03-07 13:20:31 -08001501 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001502 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1503 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001504 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505}
1506
1507void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001508{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 ATRACE_CALL();
1510 ALOGV("postComposition");
1511
Brian Anderson3546a3f2016-07-14 11:51:14 -07001512 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001513 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001514 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001515 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001516 }
1517
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001518 // |mStateLock| not needed as we are on the main thread
1519 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001520
1521 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1522 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1523 glCompositionDoneFenceTime =
1524 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1525 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1526 } else {
1527 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1528 }
1529 mGlCompositionDoneTimeline.updateSignalTimes();
1530
Brian Anderson4e606e32017-03-16 15:34:57 -07001531 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1532 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1533 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001534 mDisplayTimeline.updateSignalTimes();
1535
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1537 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1538
1539 // We use the refreshStartTime which might be sampled a little later than
1540 // when we started doing work for this frame, but that should be okay
1541 // since updateCompositorTiming has snapping logic.
1542 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001543 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001544 CompositorTiming compositorTiming;
1545 {
1546 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1547 compositorTiming = mCompositorTiming;
1548 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001549
Robert Carr2047fae2016-11-28 14:09:09 -08001550 mDrawingState.traverseInZOrder([&](Layer* layer) {
1551 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001552 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001553 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001554 recordBufferingStats(layer->getName().string(),
1555 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001556 }
Robert Carr2047fae2016-11-28 14:09:09 -08001557 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001558
Brian Anderson4e606e32017-03-16 15:34:57 -07001559 if (presentFence->isValid()) {
1560 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001561 enableHardwareVsync();
1562 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001563 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001564 }
1565 }
1566
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001567 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001568 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001569 enableHardwareVsync();
1570 }
1571 }
1572
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001573 if (mAnimCompositionPending) {
1574 mAnimCompositionPending = false;
1575
Brian Anderson4e606e32017-03-16 15:34:57 -07001576 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001577 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001578 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001579 } else {
1580 // The HWC doesn't support present fences, so use the refresh
1581 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 nsecs_t presentTime =
1583 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001584 mAnimFrameTracker.setActualPresentTime(presentTime);
1585 }
1586 mAnimFrameTracker.advanceFrame();
1587 }
Dan Stozab90cf072015-03-05 11:05:59 -08001588
1589 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1590 return;
1591 }
1592
1593 nsecs_t currentTime = systemTime();
1594 if (mHasPoweredOff) {
1595 mHasPoweredOff = false;
1596 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001597 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001599 if (numPeriods < NUM_BUCKETS - 1) {
1600 mFrameBuckets[numPeriods] += elapsedTime;
1601 } else {
1602 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1603 }
1604 mTotalTime += elapsedTime;
1605 }
1606 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607}
1608
1609void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001610 ATRACE_CALL();
1611 ALOGV("rebuildLayerStacks");
1612
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001614 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1615 ATRACE_CALL();
1616 mVisibleRegionsDirty = false;
1617 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001618
Jeff Sharkey76488112017-02-27 14:15:18 -07001619 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1620 Region opaqueRegion;
1621 Region dirtyRegion;
1622 Vector<sp<Layer>> layersSortedByZ;
1623 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1624 const Transform& tr(displayDevice->getTransform());
1625 const Rect bounds(displayDevice->getBounds());
1626 if (displayDevice->isDisplayOn()) {
1627 computeVisibleRegions(
1628 displayDevice->getLayerStack(), dirtyRegion,
1629 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001630
Jeff Sharkey76488112017-02-27 14:15:18 -07001631 mDrawingState.traverseInZOrder([&](Layer* layer) {
1632 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1633 Region drawRegion(tr.transform(
1634 layer->visibleNonTransparentRegion));
1635 drawRegion.andSelf(bounds);
1636 if (!drawRegion.isEmpty()) {
1637 layersSortedByZ.add(layer);
1638 } else {
1639 // Clear out the HWC layer if this layer was
1640 // previously visible, but no longer is
1641 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1642 nullptr);
1643 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001644 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001645 // WM changes displayDevice->layerStack upon sleep/awake.
1646 // Here we make sure we delete the HWC layers even if
1647 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001648 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1649 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001650 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001651 });
1652 }
1653 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1654 displayDevice->undefinedRegion.set(bounds);
1655 displayDevice->undefinedRegion.subtractSelf(
1656 tr.transform(opaqueRegion));
1657 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001658 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001659 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001660}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001661
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001662// pickColorMode translates a given dataspace into the best available color mode.
1663// Currently only support sRGB and Display-P3.
1664android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1665 switch (dataSpace) {
1666 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1667 // system expects.
1668 case HAL_DATASPACE_UNKNOWN:
1669 case HAL_DATASPACE_SRGB:
1670 case HAL_DATASPACE_V0_SRGB:
1671 return HAL_COLOR_MODE_SRGB;
1672 break;
1673
1674 case HAL_DATASPACE_DISPLAY_P3:
1675 return HAL_COLOR_MODE_DISPLAY_P3;
1676 break;
1677
1678 default:
1679 // TODO (courtneygo): Do we want to assert an error here?
1680 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1681 dataSpace);
1682 return HAL_COLOR_MODE_SRGB;
1683 break;
1684 }
1685}
1686
1687android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1688 // Only support sRGB and Display-P3 right now.
1689 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1690 return HAL_DATASPACE_DISPLAY_P3;
1691 }
1692 return HAL_DATASPACE_V0_SRGB;
1693}
1694
Mathias Agopiancd60f992012-08-16 16:28:27 -07001695void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001696 ATRACE_CALL();
1697 ALOGV("setUpHWComposer");
1698
Jesse Hall028dc8f2013-08-20 16:35:32 -07001699 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001700 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1701 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1702 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1703
1704 // If nothing has changed (!dirty), don't recompose.
1705 // If something changed, but we don't currently have any visible layers,
1706 // and didn't when we last did a composition, then skip it this time.
1707 // The second rule does two things:
1708 // - When all layers are removed from a display, we'll emit one black
1709 // frame, then nothing more until we get new layers.
1710 // - When a display is created with a private layer stack, we won't
1711 // emit any black frames until a layer is added to the layer stack.
1712 bool mustRecompose = dirty && !(empty && wasEmpty);
1713
1714 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1715 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1716 mustRecompose ? "doing" : "skipping",
1717 dirty ? "+" : "-",
1718 empty ? "+" : "-",
1719 wasEmpty ? "+" : "-");
1720
Dan Stoza71433162014-02-04 16:22:36 -08001721 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001722
1723 if (mustRecompose) {
1724 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1725 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001726 }
1727
Dan Stoza9e56aa02015-11-02 13:00:03 -08001728 // build the h/w work list
1729 if (CC_UNLIKELY(mGeometryInvalid)) {
1730 mGeometryInvalid = false;
1731 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1732 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1733 const auto hwcId = displayDevice->getHwcDisplayId();
1734 if (hwcId >= 0) {
1735 const Vector<sp<Layer>>& currentLayers(
1736 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001737 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001738 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001739 if (!layer->hasHwcLayer(hwcId)) {
1740 auto hwcLayer = mHwc->createLayer(hwcId);
1741 if (hwcLayer) {
1742 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1743 } else {
1744 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001745 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001746 }
1747 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001748
Robert Carrae060832016-11-28 10:51:00 -08001749 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001750 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001752 }
1753 }
1754 }
1755 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 }
Riley Andrews03414a12014-07-01 14:22:59 -07001757
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001758
1759 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1760
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 // Set the per-frame data
1762 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1763 auto& displayDevice = mDisplays[displayId];
1764 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001765
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766 if (hwcId < 0) {
1767 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001768 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001769 if (colorMatrix != mPreviousColorMatrix) {
1770 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1771 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1772 "display %zd: %d", displayId, result);
1773 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001774 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1775 layer->setPerFrameData(displayDevice);
1776 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001777
1778 if (hasWideColorDisplay) {
1779 android_color_mode newColorMode;
1780 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1781
1782 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1783 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1784 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1785 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1786 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1787 }
1788 newColorMode = pickColorMode(newDataSpace);
1789
1790 setActiveColorModeInternal(displayDevice, newColorMode);
1791 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001792 }
1793
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001794 mPreviousColorMatrix = colorMatrix;
1795
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001797 auto& displayDevice = mDisplays[displayId];
1798 if (!displayDevice->isDisplayOn()) {
1799 continue;
1800 }
1801
1802 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001803 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1804 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001805 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001806}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808void SurfaceFlinger::doComposition() {
1809 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 ALOGV("doComposition");
1811
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001812 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001813 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001814 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001815 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816 // transform the dirty region into this screen's coordinate space
1817 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001818
1819 // repaint the framebuffer (if needed)
1820 doDisplayComposition(hw, dirtyRegion);
1821
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822 hw->dirtyRegion.clear();
1823 hw->flip(hw->swapRegion);
1824 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001825 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001826 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001827 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001828}
1829
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001830void SurfaceFlinger::postFramebuffer()
1831{
Mathias Agopian841cde52012-03-01 15:44:37 -08001832 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001834
Mathias Agopiana44b0412011-10-16 18:46:35 -07001835 const nsecs_t now = systemTime();
1836 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001837
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1839 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001840 if (!displayDevice->isDisplayOn()) {
1841 continue;
1842 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 const auto hwcId = displayDevice->getHwcDisplayId();
1844 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001845 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001846 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001847 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001848 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001849 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1850 sp<Fence> releaseFence = Fence::NO_FENCE;
1851 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1852 releaseFence = displayDevice->getClientTargetAcquireFence();
1853 } else {
1854 auto hwcLayer = layer->getHwcLayer(hwcId);
1855 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001856 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 layer->onLayerDisplayed(releaseFence);
1858 }
1859 if (hwcId >= 0) {
1860 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001861 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001862 }
1863
Mathias Agopiana44b0412011-10-16 18:46:35 -07001864 mLastSwapBufferTime = systemTime() - now;
1865 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001866
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001867 // |mStateLock| not needed as we are on the main thread
1868 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001869 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1870 logFrameStats();
1871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001872}
1873
Mathias Agopian87baae12012-07-31 12:38:26 -07001874void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875{
Mathias Agopian841cde52012-03-01 15:44:37 -08001876 ATRACE_CALL();
1877
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001878 // here we keep a copy of the drawing state (that is the state that's
1879 // going to be overwritten by handleTransactionLocked()) outside of
1880 // mStateLock so that the side-effects of the State assignment
1881 // don't happen with mStateLock held (which can cause deadlocks).
1882 State drawingState(mDrawingState);
1883
Mathias Agopianca4d3602011-05-19 15:38:14 -07001884 Mutex::Autolock _l(mStateLock);
1885 const nsecs_t now = systemTime();
1886 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001887
Mathias Agopianca4d3602011-05-19 15:38:14 -07001888 // Here we're guaranteed that some transaction flags are set
1889 // so we can call handleTransactionLocked() unconditionally.
1890 // We call getTransactionFlags(), which will also clear the flags,
1891 // with mStateLock held to guarantee that mCurrentState won't change
1892 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001893
Mathias Agopiane57f2922012-08-09 16:29:12 -07001894 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001895 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001896
Mathias Agopianca4d3602011-05-19 15:38:14 -07001897 mLastTransactionTime = systemTime() - now;
1898 mDebugInTransaction = 0;
1899 invalidateHwcGeometry();
1900 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001901}
1902
Mathias Agopian87baae12012-07-31 12:38:26 -07001903void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001904{
Dan Stoza7dde5992015-05-22 09:51:44 -07001905 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001906 mCurrentState.traverseInZOrder([](Layer* layer) {
1907 layer->notifyAvailableFrames();
1908 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001910 /*
1911 * Traversal of the children
1912 * (perform the transaction for each of them if needed)
1913 */
1914
Mathias Agopian3559b072012-08-15 13:46:03 -07001915 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001916 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001917 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001918 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001919
1920 const uint32_t flags = layer->doTransaction(0);
1921 if (flags & Layer::eVisibleRegion)
1922 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001923 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001924 }
1925
1926 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001927 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001928 */
1929
Mathias Agopiane57f2922012-08-09 16:29:12 -07001930 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001931 // here we take advantage of Vector's copy-on-write semantics to
1932 // improve performance by skipping the transaction entirely when
1933 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001934 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1935 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001936 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001937 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001938 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001939 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001940
1941 // find the displays that were removed
1942 // (ie: in drawing state but not in current state)
1943 // also handle displays that changed
1944 // (ie: displays that are in both lists)
1945 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001946 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1947 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001948 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001949 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001950 // Call makeCurrent() on the primary display so we can
1951 // be sure that nothing associated with this display
1952 // is current.
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001953 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001954 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001955 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1956 if (hw != NULL)
1957 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001958 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001959 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001960 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001961 } else {
1962 ALOGW("trying to remove the main display");
1963 }
1964 } else {
1965 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001966 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001967 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001968 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1969 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001970 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001971 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001972 // recreating the DisplayDevice, so we just remove it
1973 // from the drawing state, so that it get re-added
1974 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001975 sp<DisplayDevice> hw(getDisplayDevice(display));
1976 if (hw != NULL)
1977 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001978 mDisplays.removeItem(display);
1979 mDrawingState.displays.removeItemsAt(i);
1980 dc--; i--;
1981 // at this point we must loop to the next item
1982 continue;
1983 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001984
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001985 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001986 if (disp != NULL) {
1987 if (state.layerStack != draw[i].layerStack) {
1988 disp->setLayerStack(state.layerStack);
1989 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001990 if ((state.orientation != draw[i].orientation)
1991 || (state.viewport != draw[i].viewport)
1992 || (state.frame != draw[i].frame))
1993 {
1994 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001995 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001996 }
Michael Lentine47e45402014-07-18 15:34:25 -07001997 if (state.width != draw[i].width || state.height != draw[i].height) {
1998 disp->setDisplaySize(state.width, state.height);
1999 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002000 }
2001 }
2002 }
2003
2004 // find displays that were added
2005 // (ie: in current state but not in drawing state)
2006 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002007 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002008 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002009
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002010 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002011 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002012 sp<IGraphicBufferProducer> bqProducer;
2013 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00002014 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
2015 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002016
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002018 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002019 // Virtual displays without a surface are dormant:
2020 // they have external state (layer stack, projection,
2021 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002022 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002023
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002024 // Allow VR composer to use virtual displays.
2025 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002026 int width = 0;
2027 int status = state.surface->query(
2028 NATIVE_WINDOW_WIDTH, &width);
2029 ALOGE_IF(status != NO_ERROR,
2030 "Unable to query width (%d)", status);
2031 int height = 0;
2032 status = state.surface->query(
2033 NATIVE_WINDOW_HEIGHT, &height);
2034 ALOGE_IF(status != NO_ERROR,
2035 "Unable to query height (%d)", status);
2036 int intFormat = 0;
2037 status = state.surface->query(
2038 NATIVE_WINDOW_FORMAT, &intFormat);
2039 ALOGE_IF(status != NO_ERROR,
2040 "Unable to query format (%d)", status);
2041 auto format = static_cast<android_pixel_format_t>(
2042 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002043
Dan Stoza8cf150a2016-08-02 10:27:31 -07002044 mHwc->allocateVirtualDisplay(width, height, &format,
2045 &hwcId);
2046 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047
Dan Stoza5cf424b2016-05-20 14:02:39 -07002048 // TODO: Plumb requested format back up to consumer
2049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 sp<VirtualDisplaySurface> vds =
2051 new VirtualDisplaySurface(*mHwc,
2052 hwcId, state.surface, bqProducer,
2053 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002054
2055 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002056 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002057 }
2058 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002059 ALOGE_IF(state.surface!=NULL,
2060 "adding a supported display, but rendering "
2061 "surface is provided (%p), ignoring it",
2062 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002063
2064 hwcId = state.type;
2065 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2066 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002067 }
2068
2069 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002070 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002071 sp<DisplayDevice> hw =
2072 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2073 dispSurface, producer,
2074 mRenderEngine->getEGLConfig(),
2075 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002076 hw->setLayerStack(state.layerStack);
2077 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002078 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002079 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002080 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002082 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002083 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002084 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002085 }
2086 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002089
Mathias Agopian84300952012-11-21 16:02:13 -08002090 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2091 // The transform hint might have changed for some layers
2092 // (either because a display has changed, or because a layer
2093 // as changed).
2094 //
2095 // Walk through all the layers in currentLayers,
2096 // and update their transform hint.
2097 //
2098 // If a layer is visible only on a single display, then that
2099 // display is used to calculate the hint, otherwise we use the
2100 // default display.
2101 //
2102 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2103 // the hint is set before we acquire a buffer from the surface texture.
2104 //
2105 // NOTE: layer transactions have taken place already, so we use their
2106 // drawing state. However, SurfaceFlinger's own transaction has not
2107 // happened yet, so we must use the current state layer list
2108 // (soon to become the drawing state list).
2109 //
2110 sp<const DisplayDevice> disp;
2111 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002112 bool first = true;
2113 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002114 // NOTE: we rely on the fact that layers are sorted by
2115 // layerStack first (so we don't have to traverse the list
2116 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002117 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002118 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002119 currentlayerStack = layerStack;
2120 // figure out if this layerstack is mirrored
2121 // (more than one display) if so, pick the default display,
2122 // if not, pick the only display it's on.
2123 disp.clear();
2124 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2125 sp<const DisplayDevice> hw(mDisplays[dpy]);
2126 if (hw->getLayerStack() == currentlayerStack) {
2127 if (disp == NULL) {
2128 disp = hw;
2129 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002130 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002131 break;
2132 }
2133 }
2134 }
2135 }
Chet Haase91d25932013-04-11 15:24:55 -07002136 if (disp == NULL) {
2137 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2138 // redraw after transform hint changes. See bug 8508397.
2139
2140 // could be null when this layer is using a layerStack
2141 // that is not visible on any display. Also can occur at
2142 // screen off/on times.
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07002143 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002144 }
Chet Haase91d25932013-04-11 15:24:55 -07002145 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002146
2147 first = false;
2148 });
Mathias Agopian84300952012-11-21 16:02:13 -08002149 }
2150
2151
Mathias Agopian3559b072012-08-15 13:46:03 -07002152 /*
2153 * Perform our own transaction if needed
2154 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002155
2156 if (mLayersAdded) {
2157 mLayersAdded = false;
2158 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002159 mVisibleRegionsDirty = true;
2160 }
2161
2162 // some layers might have been removed, so
2163 // we need to update the regions they're exposing.
2164 if (mLayersRemoved) {
2165 mLayersRemoved = false;
2166 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002167 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002168 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002169 // this layer is not visible anymore
2170 // TODO: we could traverse the tree from front to back and
2171 // compute the actual visible region
2172 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002173 Region visibleReg;
2174 visibleReg.set(layer->computeScreenBounds());
2175 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002176 }
Robert Carr2047fae2016-11-28 14:09:09 -08002177 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178 }
2179
2180 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002181
2182 updateCursorAsync();
2183}
2184
2185void SurfaceFlinger::updateCursorAsync()
2186{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2188 auto& displayDevice = mDisplays[displayId];
2189 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002190 continue;
2191 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192
2193 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2194 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002195 }
2196 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002197}
2198
2199void SurfaceFlinger::commitTransaction()
2200{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002201 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002202 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002203 for (const auto& l : mLayersPendingRemoval) {
2204 recordBufferingStats(l->getName().string(),
2205 l->getOccupancyHistory(true));
2206 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002207 }
2208 mLayersPendingRemoval.clear();
2209 }
2210
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002211 // If this transaction is part of a window animation then the next frame
2212 // we composite should be considered an animation as well.
2213 mAnimCompositionPending = mAnimTransactionPending;
2214
Mathias Agopian4fec8732012-06-29 14:12:52 -07002215 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002216 mDrawingState.traverseInZOrder([](Layer* layer) {
2217 layer->commitChildList();
2218 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002219 mTransactionPending = false;
2220 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002221 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222}
2223
Robert Carr2047fae2016-11-28 14:09:09 -08002224void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002225 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226{
Mathias Agopian841cde52012-03-01 15:44:37 -08002227 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 Region aboveOpaqueLayers;
2231 Region aboveCoveredLayers;
2232 Region dirty;
2233
Mathias Agopian87baae12012-07-31 12:38:26 -07002234 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Robert Carr2047fae2016-11-28 14:09:09 -08002236 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002238 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239
Jesse Hall01e29052013-02-19 16:13:35 -08002240 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002241 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002242 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002243
Mathias Agopianab028732010-03-16 16:41:46 -07002244 /*
2245 * opaqueRegion: area of a surface that is fully opaque.
2246 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002248
2249 /*
2250 * visibleRegion: area of a surface that is visible on screen
2251 * and not fully transparent. This is essentially the layer's
2252 * footprint minus the opaque regions above it.
2253 * Areas covered by a translucent surface are considered visible.
2254 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002256
2257 /*
2258 * coveredRegion: area of a surface that is covered by all
2259 * visible regions above it (which includes the translucent areas).
2260 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002262
Jesse Halla8026d22012-09-25 13:25:04 -07002263 /*
2264 * transparentRegion: area of a surface that is hinted to be completely
2265 * transparent. This is only used to tell when the layer has no visible
2266 * non-transparent regions and can be removed from the layer list. It
2267 * does not affect the visibleRegion of this layer or any layers
2268 * beneath it. The hint may not be correct if apps don't respect the
2269 * SurfaceView restrictions (which, sadly, some don't).
2270 */
2271 Region transparentRegion;
2272
Mathias Agopianab028732010-03-16 16:41:46 -07002273
2274 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002275 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002276 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002279 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002280 if (!visibleRegion.isEmpty()) {
2281 // Remove the transparent area from the visible region
2282 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002283 if (tr.preserveRects()) {
2284 // transform the transparent region
2285 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002287 // transformation too complex, can't do the
2288 // transparent region optimization.
2289 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 }
Mathias Agopianab028732010-03-16 16:41:46 -07002291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292
Mathias Agopianab028732010-03-16 16:41:46 -07002293 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002295 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002296 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2297 // the opaque region is the layer's footprint
2298 opaqueRegion = visibleRegion;
2299 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 }
2301 }
2302
Mathias Agopianab028732010-03-16 16:41:46 -07002303 // Clip the covered region to the visible region
2304 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2305
2306 // Update aboveCoveredLayers for next (lower) layer
2307 aboveCoveredLayers.orSelf(visibleRegion);
2308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309 // subtract the opaque region covered by the layers above us
2310 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311
2312 // compute this layer's dirty region
2313 if (layer->contentDirty) {
2314 // we need to invalidate the whole region
2315 dirty = visibleRegion;
2316 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002317 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318 layer->contentDirty = false;
2319 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002320 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002321 * the exposed region consists of two components:
2322 * 1) what's VISIBLE now and was COVERED before
2323 * 2) what's EXPOSED now less what was EXPOSED before
2324 *
2325 * note that (1) is conservative, we start with the whole
2326 * visible region but only keep what used to be covered by
2327 * something -- which mean it may have been exposed.
2328 *
2329 * (2) handles areas that were not covered by anything but got
2330 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002331 */
Mathias Agopianab028732010-03-16 16:41:46 -07002332 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002333 const Region oldVisibleRegion = layer->visibleRegion;
2334 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002335 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2336 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 }
2338 dirty.subtractSelf(aboveOpaqueLayers);
2339
2340 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002341 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342
Mathias Agopianab028732010-03-16 16:41:46 -07002343 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002345
Jesse Halla8026d22012-09-25 13:25:04 -07002346 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 layer->setVisibleRegion(visibleRegion);
2348 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002349 layer->setVisibleNonTransparentRegion(
2350 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002351 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352
Mathias Agopian87baae12012-07-31 12:38:26 -07002353 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2357 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002358 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002359 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2360 if (hw->getLayerStack() == layerStack) {
2361 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002362 }
2363 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002364}
2365
Dan Stoza6b9454d2014-11-07 16:00:59 -08002366bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 ALOGV("handlePageFlip");
2369
Brian Andersond6927fb2016-07-23 23:37:30 -07002370 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371
Mathias Agopian4fec8732012-06-29 14:12:52 -07002372 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002373 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002374
2375 // Store the set of layers that need updates. This set must not change as
2376 // buffers are being latched, as this could result in a deadlock.
2377 // Example: Two producers share the same command stream and:
2378 // 1.) Layer 0 is latched
2379 // 2.) Layer 0 gets a new frame
2380 // 2.) Layer 1 gets a new frame
2381 // 3.) Layer 1 is latched.
2382 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2383 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002384 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002385 if (layer->hasQueuedFrame()) {
2386 frameQueued = true;
2387 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002388 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002389 } else {
2390 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002391 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002392 } else {
2393 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002394 }
Robert Carr2047fae2016-11-28 14:09:09 -08002395 });
2396
Dan Stoza9e56aa02015-11-02 13:00:03 -08002397 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002398 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002399 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002400 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002401 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002402
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002403 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002404
2405 // If we will need to wake up at some time in the future to deal with a
2406 // queued frame that shouldn't be displayed during this vsync period, wake
2407 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002408 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002409 signalLayerUpdate();
2410 }
2411
2412 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002413 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414}
2415
Mathias Agopianad456f92011-01-13 17:53:01 -08002416void SurfaceFlinger::invalidateHwcGeometry()
2417{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002419}
2420
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002421
Fabien Sanglard830b8472016-11-30 16:35:58 -08002422void SurfaceFlinger::doDisplayComposition(
2423 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002424 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002425{
Dan Stoza71433162014-02-04 16:22:36 -08002426 // We only need to actually compose the display if:
2427 // 1) It is being handled by hardware composer, which may need this to
2428 // keep its virtual display state machine in sync, or
2429 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002430 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002431 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002433 return;
2434 }
2435
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 ALOGV("doDisplayComposition");
2437
Mathias Agopian87baae12012-07-31 12:38:26 -07002438 Region dirtyRegion(inDirtyRegion);
2439
Mathias Agopianb8a55602009-06-26 19:06:36 -07002440 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002441 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442
Fabien Sanglard830b8472016-11-30 16:35:58 -08002443 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002444 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002445 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2446 // takes a rectangle, we must make sure to update that whole
2447 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002448 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002449 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002450 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002451 // We need to redraw the rectangle that will be updated
2452 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002453 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002454 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002455 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002456 } else {
2457 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002458 dirtyRegion.set(displayDevice->bounds());
2459 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 }
2461 }
2462
Fabien Sanglard830b8472016-11-30 16:35:58 -08002463 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002465 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002466 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002467
2468 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002469 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470}
2471
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472bool SurfaceFlinger::doComposeSurfaces(
2473 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002474{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002475 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002476
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002478
2479 mat4 oldColorMatrix;
2480 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2481 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2482 if (applyColorMatrix) {
2483 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2484 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2485 }
2486
Dan Stoza9e56aa02015-11-02 13:00:03 -08002487 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2488 if (hasClientComposition) {
2489 ALOGV("hasClientComposition");
2490
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002491#ifdef USE_HWC2
2492 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2493 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2494#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002496 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002498 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07002499
2500 // |mStateLock| not needed as we are on the main thread
2501 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002502 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2503 }
2504 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002505 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002506
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002507 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002508 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2509 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002510 // when using overlays, we assume a fully transparent framebuffer
2511 // NOTE: we could reduce how much we need to clear, for instance
2512 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002513 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002514 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002516 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002517 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002518 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002519
2520 // we remove the scissor part
2521 // we're left with the letterbox region
2522 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002524
2525 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002527
2528 // but limit it to the dirty region
2529 region.andSelf(dirty);
2530
Mathias Agopianb9494d52012-04-18 02:28:45 -07002531 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002532 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002533 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002535 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002536 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002537
Dan Stoza9e56aa02015-11-02 13:00:03 -08002538 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002539 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002540 // scissor on the main display. It should never be needed
2541 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 const Rect& bounds(displayDevice->getBounds());
2543 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002544 if (scissor != bounds) {
2545 // scissor doesn't match the screen's dimensions, so we
2546 // need to clear everything outside of it and enable
2547 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002548
Mathias Agopianf45c5102012-10-24 16:29:17 -07002549 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550 const uint32_t height = displayDevice->getHeight();
2551 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002552 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002553 }
2554 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002555 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002556
Mathias Agopian85d751c2012-08-29 16:59:24 -07002557 /*
2558 * and then, render the layers targeted at the framebuffer
2559 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002560
Dan Stoza9e56aa02015-11-02 13:00:03 -08002561 ALOGV("Rendering client layers");
2562 const Transform& displayTransform = displayDevice->getTransform();
2563 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002564 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 bool firstLayer = true;
2566 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2567 const Region clip(dirty.intersect(
2568 displayTransform.transform(layer->visibleRegion)));
2569 ALOGV("Layer: %s", layer->getName().string());
2570 ALOGV(" Composition type: %s",
2571 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002572 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 switch (layer->getCompositionType(hwcId)) {
2574 case HWC2::Composition::Cursor:
2575 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002576 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002578 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2580 layer->isOpaque(state) && (state.alpha == 1.0f)
2581 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002582 // never clear the very first layer since we're
2583 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002584 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002585 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002586 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002587 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588 case HWC2::Composition::Client: {
2589 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002590 break;
2591 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002593 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002594 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 } else {
2596 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002597 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002599 }
2600 } else {
2601 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002603 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002605 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002607 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002608 }
2609 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002610
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002611 if (applyColorMatrix) {
2612 getRenderEngine().setupColorTransform(oldColorMatrix);
2613 }
2614
Mathias Agopianf45c5102012-10-24 16:29:17 -07002615 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002617 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002618}
2619
Fabien Sanglard830b8472016-11-30 16:35:58 -08002620void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2621 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002622 RenderEngine& engine(getRenderEngine());
2623 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624}
2625
Dan Stoza7d89d062015-04-30 13:29:25 -07002626status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002627 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002628 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002629 const sp<Layer>& lbc,
2630 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002631{
Dan Stoza7d89d062015-04-30 13:29:25 -07002632 // add this layer to the current state list
2633 {
2634 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002635 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002636 return NO_MEMORY;
2637 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002638 if (parent == nullptr) {
2639 mCurrentState.layersSortedByZ.add(lbc);
2640 } else {
2641 parent->addChild(lbc);
2642 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002643 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 mLayersAdded = true;
2645 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002646 }
2647
Mathias Agopian96f08192010-06-02 23:28:45 -07002648 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002649 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002650
Dan Stoza7d89d062015-04-30 13:29:25 -07002651 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002652}
2653
Robert Carr9524cb32017-02-13 11:32:32 -08002654status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002655 Mutex::Autolock _l(mStateLock);
2656
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 const auto& p = layer->getParent();
2658 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2659 mCurrentState.layersSortedByZ.remove(layer);
2660
Robert Carr136e2f62017-02-08 17:54:29 -08002661 // As a matter of normal operation, the LayerCleaner will produce a second
2662 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2663 // so we will succeed in promoting it, but it's already been removed
2664 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2665 // otherwise something has gone wrong and we are leaking the layer.
2666 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002667 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2668 layer->getName().string(),
2669 (p != nullptr) ? p->getName().string() : "no-parent");
2670 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002671 } else if (index < 0) {
2672 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002673 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002674
2675 mLayersPendingRemoval.add(layer);
2676 mLayersRemoved = true;
2677 mNumLayers--;
2678 setTransactionFlags(eTransactionNeeded);
2679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680}
2681
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002682uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002683 return android_atomic_release_load(&mTransactionFlags);
2684}
2685
Mathias Agopian3f844832013-08-07 21:24:32 -07002686uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2688}
2689
Mathias Agopian3f844832013-08-07 21:24:32 -07002690uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2692 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002693 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694 }
2695 return old;
2696}
2697
Mathias Agopian8b33f032012-07-24 20:43:54 -07002698void SurfaceFlinger::setTransactionState(
2699 const Vector<ComposerState>& state,
2700 const Vector<DisplayState>& displays,
2701 uint32_t flags)
2702{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002703 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002704 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002705 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002706
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002707 if (flags & eAnimation) {
2708 // For window updates that are part of an animation we must wait for
2709 // previous animation "frames" to be handled.
2710 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002711 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002712 if (CC_UNLIKELY(err != NO_ERROR)) {
2713 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002714 // caller after a few seconds.
2715 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2716 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002717 mAnimTransactionPending = false;
2718 break;
2719 }
2720 }
2721 }
2722
Mathias Agopiane57f2922012-08-09 16:29:12 -07002723 size_t count = displays.size();
2724 for (size_t i=0 ; i<count ; i++) {
2725 const DisplayState& s(displays[i]);
2726 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002727 }
2728
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002730 for (size_t i=0 ; i<count ; i++) {
2731 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002732 // Here we need to check that the interface we're given is indeed
2733 // one of our own. A malicious client could give us a NULL
2734 // IInterface, or one of its own or even one of our own but a
2735 // different type. All these situations would cause us to crash.
2736 //
2737 // NOTE: it would be better to use RTTI as we could directly check
2738 // that we have a Client*. however, RTTI is disabled in Android.
2739 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002740 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002741 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002742 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002743 sp<Client> client( static_cast<Client *>(s.client.get()) );
2744 transactionFlags |= setClientStateLocked(client, s.state);
2745 }
2746 }
2747 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002748 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002749
Robert Carr2a7dbb42016-05-24 11:41:28 -07002750 // If a synchronous transaction is explicitly requested without any changes,
2751 // force a transaction anyway. This can be used as a flush mechanism for
2752 // previous async transactions.
2753 if (transactionFlags == 0 && (flags & eSynchronous)) {
2754 transactionFlags = eTransactionNeeded;
2755 }
2756
Mathias Agopian386aa982011-11-07 21:58:03 -08002757 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002758 if (mInterceptor.isEnabled()) {
2759 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2760 }
Irvel468051e2016-06-13 16:44:44 -07002761
Mathias Agopian386aa982011-11-07 21:58:03 -08002762 // this triggers the transaction
2763 setTransactionFlags(transactionFlags);
2764
2765 // if this is a synchronous transaction, wait for it to take effect
2766 // before returning.
2767 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002768 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002769 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002770 if (flags & eAnimation) {
2771 mAnimTransactionPending = true;
2772 }
2773 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002774 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2775 if (CC_UNLIKELY(err != NO_ERROR)) {
2776 // just in case something goes wrong in SF, return to the
2777 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002778 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2779 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002780 break;
2781 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 }
2784}
2785
Mathias Agopiane57f2922012-08-09 16:29:12 -07002786uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2787{
Jesse Hall9a143922012-10-04 16:29:19 -07002788 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2789 if (dpyIdx < 0)
2790 return 0;
2791
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002793 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002794 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002795 const uint32_t what = s.what;
2796 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002797 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002798 disp.surface = s.surface;
2799 flags |= eDisplayTransactionNeeded;
2800 }
2801 }
2802 if (what & DisplayState::eLayerStackChanged) {
2803 if (disp.layerStack != s.layerStack) {
2804 disp.layerStack = s.layerStack;
2805 flags |= eDisplayTransactionNeeded;
2806 }
2807 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002808 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002809 if (disp.orientation != s.orientation) {
2810 disp.orientation = s.orientation;
2811 flags |= eDisplayTransactionNeeded;
2812 }
2813 if (disp.frame != s.frame) {
2814 disp.frame = s.frame;
2815 flags |= eDisplayTransactionNeeded;
2816 }
2817 if (disp.viewport != s.viewport) {
2818 disp.viewport = s.viewport;
2819 flags |= eDisplayTransactionNeeded;
2820 }
2821 }
Michael Lentine47e45402014-07-18 15:34:25 -07002822 if (what & DisplayState::eDisplaySizeChanged) {
2823 if (disp.width != s.width) {
2824 disp.width = s.width;
2825 flags |= eDisplayTransactionNeeded;
2826 }
2827 if (disp.height != s.height) {
2828 disp.height = s.height;
2829 flags |= eDisplayTransactionNeeded;
2830 }
2831 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002832 }
2833 return flags;
2834}
2835
2836uint32_t SurfaceFlinger::setClientStateLocked(
2837 const sp<Client>& client,
2838 const layer_state_t& s)
2839{
2840 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002841 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002842 if (layer != 0) {
2843 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002844 bool geometryAppliesWithResize =
2845 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002846 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002847 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002848 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002849 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002850 }
2851 if (what & layer_state_t::eLayerChanged) {
2852 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 const auto& p = layer->getParent();
2854 if (p == nullptr) {
2855 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2856 if (layer->setLayer(s.z) && idx >= 0) {
2857 mCurrentState.layersSortedByZ.removeAt(idx);
2858 mCurrentState.layersSortedByZ.add(layer);
2859 // we need traversal (state changed)
2860 // AND transaction (list changed)
2861 flags |= eTransactionNeeded|eTraversalNeeded;
2862 }
2863 } else {
2864 if (p->setChildLayer(layer, s.z)) {
2865 flags |= eTransactionNeeded|eTraversalNeeded;
2866 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002867 }
2868 }
2869 if (what & layer_state_t::eSizeChanged) {
2870 if (layer->setSize(s.w, s.h)) {
2871 flags |= eTraversalNeeded;
2872 }
2873 }
2874 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002875 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002876 flags |= eTraversalNeeded;
2877 }
2878 if (what & layer_state_t::eMatrixChanged) {
2879 if (layer->setMatrix(s.matrix))
2880 flags |= eTraversalNeeded;
2881 }
2882 if (what & layer_state_t::eTransparentRegionChanged) {
2883 if (layer->setTransparentRegionHint(s.transparentRegion))
2884 flags |= eTraversalNeeded;
2885 }
Dan Stoza23116082015-06-18 14:58:39 -07002886 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002887 if (layer->setFlags(s.flags, s.mask))
2888 flags |= eTraversalNeeded;
2889 }
2890 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002891 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002892 flags |= eTraversalNeeded;
2893 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002894 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002895 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002896 flags |= eTraversalNeeded;
2897 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002899 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002900 // We only allow setting layer stacks for top level layers,
2901 // everything else inherits layer stack from its parent.
2902 if (layer->hasParent()) {
2903 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2904 layer->getName().string());
2905 } else if (idx < 0) {
2906 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2907 "that also does not appear in the top level layer list. Something"
2908 " has gone wrong.", layer->getName().string());
2909 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 mCurrentState.layersSortedByZ.removeAt(idx);
2911 mCurrentState.layersSortedByZ.add(layer);
2912 // we need traversal (state changed)
2913 // AND transaction (list changed)
2914 flags |= eTransactionNeeded|eTraversalNeeded;
2915 }
2916 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002917 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002918 if (s.barrierHandle != nullptr) {
2919 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2920 } else if (s.barrierGbp != nullptr) {
2921 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2922 if (authenticateSurfaceTextureLocked(gbp)) {
2923 const auto& otherLayer =
2924 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2925 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2926 } else {
2927 ALOGE("Attempt to defer transaction to to an"
2928 " unrecognized GraphicBufferProducer");
2929 }
2930 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002931 // We don't trigger a traversal here because if no other state is
2932 // changed, we don't want this to cause any more work
2933 }
Robert Carr1db73f62016-12-21 12:58:51 -08002934 if (what & layer_state_t::eReparentChildren) {
2935 if (layer->reparentChildren(s.reparentHandle)) {
2936 flags |= eTransactionNeeded|eTraversalNeeded;
2937 }
2938 }
Robert Carr9524cb32017-02-13 11:32:32 -08002939 if (what & layer_state_t::eDetachChildren) {
2940 layer->detachChildren();
2941 }
Robert Carrc3574f72016-03-24 12:19:32 -07002942 if (what & layer_state_t::eOverrideScalingModeChanged) {
2943 layer->setOverrideScalingMode(s.overrideScalingMode);
2944 // We don't trigger a traversal here because if no other state is
2945 // changed, we don't want this to cause any more work
2946 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002947 }
2948 return flags;
2949}
2950
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002951status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002952 const String8& name,
2953 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002954 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002955 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2956 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002958 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002959 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002960 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002961 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002962 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002963
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002964 status_t result = NO_ERROR;
2965
2966 sp<Layer> layer;
2967
Cody Northropbc755282017-03-31 12:00:08 -06002968 String8 uniqueName = getUniqueLayerName(name);
2969
Mathias Agopian3165cc22012-08-08 19:42:09 -07002970 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2971 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002972 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002973 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002974 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002976 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002977 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002978 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002979 handle, gbp, &layer);
2980 break;
2981 default:
2982 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 break;
2984 }
2985
Dan Stoza7d89d062015-04-30 13:29:25 -07002986 if (result != NO_ERROR) {
2987 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002989
Albert Chaulk479c60c2017-01-27 14:21:34 -05002990 layer->setInfo(windowType, ownerUid);
2991
Robert Carr1f0a16a2016-10-24 16:27:39 -07002992 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002993 if (result != NO_ERROR) {
2994 return result;
2995 }
Irvelffc9efc2016-07-27 15:16:37 -07002996 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002997
2998 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002999 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000}
3001
Cody Northropbc755282017-03-31 12:00:08 -06003002String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3003{
3004 bool matchFound = true;
3005 uint32_t dupeCounter = 0;
3006
3007 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3008 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3009
3010 // Loop over layers until we're sure there is no matching name
3011 while (matchFound) {
3012 matchFound = false;
3013 mDrawingState.traverseInZOrder([&](Layer* layer) {
3014 if (layer->getName() == uniqueName) {
3015 matchFound = true;
3016 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3017 }
3018 });
3019 }
3020
3021 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3022
3023 return uniqueName;
3024}
3025
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003026status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3027 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3028 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003029{
3030 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003031 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 case PIXEL_FORMAT_TRANSPARENT:
3033 case PIXEL_FORMAT_TRANSLUCENT:
3034 format = PIXEL_FORMAT_RGBA_8888;
3035 break;
3036 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003037 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 break;
3039 }
3040
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003041 *outLayer = new Layer(this, client, name, w, h, flags);
3042 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3043 if (err == NO_ERROR) {
3044 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003045 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003047
3048 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3049 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050}
3051
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003052status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3053 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3054 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003056 *outLayer = new LayerDim(this, client, name, w, h, flags);
3057 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003058 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003059 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003060}
3061
Mathias Agopianac9fa422013-02-11 16:40:36 -08003062status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063{
Robert Carr9524cb32017-02-13 11:32:32 -08003064 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003065 status_t err = NO_ERROR;
3066 sp<Layer> l(client->getLayerUser(handle));
3067 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003068 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003069 err = removeLayer(l);
3070 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3071 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003072 }
3073 return err;
3074}
3075
Mathias Agopian13127d82013-03-05 17:47:11 -08003076status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003077{
Mathias Agopian67106042013-03-14 19:18:13 -07003078 // called by ~LayerCleaner() when all references to the IBinder (handle)
3079 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003080 sp<Layer> l = layer.promote();
3081 if (l == nullptr) {
3082 // The layer has already been removed, carry on
3083 return NO_ERROR;
3084 } if (l->getParent() != nullptr) {
3085 // If we have a parent, then we can continue to live as long as it does.
3086 return NO_ERROR;
3087 }
3088 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089}
3090
Mathias Agopianb60314a2012-04-10 22:09:54 -07003091// ---------------------------------------------------------------------------
3092
Andy McFadden13a082e2012-08-24 10:16:42 -07003093void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003094 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003095 Vector<ComposerState> state;
3096 Vector<DisplayState> displays;
3097 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003098 d.what = DisplayState::eDisplayProjectionChanged |
3099 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003100 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003101 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003102 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003103 d.frame.makeInvalid();
3104 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003105 d.width = 0;
3106 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003107 displays.add(d);
3108 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003109 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003110
Dan Stoza9e56aa02015-11-02 13:00:03 -08003111 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3112 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003113 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003114
Brian Andersond0010582017-03-07 13:20:31 -08003115 // Use phase of 0 since phase is not known.
3116 // Use latency of 0, which will snap to the ideal latency.
3117 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003118}
3119
3120void SurfaceFlinger::initializeDisplays() {
3121 class MessageScreenInitialized : public MessageBase {
3122 SurfaceFlinger* flinger;
3123 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003124 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003125 virtual bool handler() {
3126 flinger->onInitializeDisplays();
3127 return true;
3128 }
3129 };
3130 sp<MessageBase> msg = new MessageScreenInitialized(this);
3131 postMessageAsync(msg); // we may be called from main thread, use async message
3132}
3133
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003134void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3135 int mode) {
3136 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3137 this);
3138 int32_t type = hw->getDisplayType();
3139 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003140
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003141 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003142 return;
3143 }
3144
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003145 hw->setPowerMode(mode);
3146 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3147 ALOGW("Trying to set power mode for virtual display");
3148 return;
3149 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003150
Irvelffc9efc2016-07-27 15:16:37 -07003151 if (mInterceptor.isEnabled()) {
3152 Mutex::Autolock _l(mStateLock);
3153 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3154 if (idx < 0) {
3155 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3156 return;
3157 }
3158 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3159 }
3160
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003161 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003162 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003163 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003164 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3165 // FIXME: eventthread only knows about the main display right now
3166 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003167 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003170 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003171 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003172 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003173
3174 struct sched_param param = {0};
3175 param.sched_priority = 1;
3176 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3177 ALOGW("Couldn't set SCHED_FIFO on display on");
3178 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003179 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003180 // Turn off the display
3181 struct sched_param param = {0};
3182 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3183 ALOGW("Couldn't set SCHED_OTHER on display off");
3184 }
3185
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003186 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003187 disableHardwareVsync(true); // also cancels any in-progress resync
3188
Mathias Agopiancde87a32012-09-13 14:09:01 -07003189 // FIXME: eventthread only knows about the main display right now
3190 mEventThread->onScreenReleased();
3191 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003192
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003193 getHwComposer().setPowerMode(type, mode);
3194 mVisibleRegionsDirty = true;
3195 // from this point on, SF will stop drawing on this display
3196 } else {
3197 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003198 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003199}
3200
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003201void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3202 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003203 SurfaceFlinger& mFlinger;
3204 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003205 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003206 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003207 MessageSetPowerMode(SurfaceFlinger& flinger,
3208 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3209 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003210 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003211 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003212 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003214 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003215 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003216 ALOGW("Attempt to set power mode = %d for virtual display",
3217 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003218 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003219 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003220 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003221 return true;
3222 }
3223 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003224 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003225 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003226}
3227
3228// ---------------------------------------------------------------------------
3229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3231{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003233
Mathias Agopianbd115332013-04-18 16:41:04 -07003234 IPCThreadState* ipc = IPCThreadState::self();
3235 const int pid = ipc->getCallingPid();
3236 const int uid = ipc->getCallingUid();
3237 if ((uid != AID_SHELL) &&
3238 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003239 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003240 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003242 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003243 // (this would indicate SF is stuck, but we want to be able to
3244 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003245 status_t err = mStateLock.timedLock(s2ns(1));
3246 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003247 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003248 result.appendFormat(
3249 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3250 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003251 }
3252
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003253 bool dumpAll = true;
3254 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003255 size_t numArgs = args.size();
3256 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003257 if ((index < numArgs) &&
3258 (args[index] == String16("--list"))) {
3259 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003260 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003261 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003262 }
3263
3264 if ((index < numArgs) &&
3265 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003266 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003267 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003268 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003269 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003270
3271 if ((index < numArgs) &&
3272 (args[index] == String16("--latency-clear"))) {
3273 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003274 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003275 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003276 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003277
3278 if ((index < numArgs) &&
3279 (args[index] == String16("--dispsync"))) {
3280 index++;
3281 mPrimaryDispSync.dump(result);
3282 dumpAll = false;
3283 }
Dan Stozab90cf072015-03-05 11:05:59 -08003284
3285 if ((index < numArgs) &&
3286 (args[index] == String16("--static-screen"))) {
3287 index++;
3288 dumpStaticScreenStats(result);
3289 dumpAll = false;
3290 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003291
3292 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003293 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003294 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003295 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003296 dumpAll = false;
3297 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003298
3299 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3300 index++;
3301 dumpWideColorInfo(result);
3302 dumpAll = false;
3303 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003304 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003305
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003306 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003307 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003308 }
3309
Mathias Agopian9795c422009-08-26 16:36:26 -07003310 if (locked) {
3311 mStateLock.unlock();
3312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313 }
3314 write(fd, result.string(), result.size());
3315 return NO_ERROR;
3316}
3317
Dan Stozac7014012014-02-14 15:03:43 -08003318void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3319 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003320{
Robert Carr2047fae2016-11-28 14:09:09 -08003321 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003322 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003323 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003324}
3325
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003326void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003327 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003328{
3329 String8 name;
3330 if (index < args.size()) {
3331 name = String8(args[index]);
3332 index++;
3333 }
3334
Dan Stoza9e56aa02015-11-02 13:00:03 -08003335 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3336 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003337 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003338
3339 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003340 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003341 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003342 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003343 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003344 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003345 }
Robert Carr2047fae2016-11-28 14:09:09 -08003346 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003347 }
3348}
3349
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003350void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003351 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003352{
3353 String8 name;
3354 if (index < args.size()) {
3355 name = String8(args[index]);
3356 index++;
3357 }
3358
Robert Carr2047fae2016-11-28 14:09:09 -08003359 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003360 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003361 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003362 }
Robert Carr2047fae2016-11-28 14:09:09 -08003363 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003364
Svetoslavd85084b2014-03-20 10:28:31 -07003365 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003366}
3367
Jamie Gennis6547ff42013-07-16 20:12:42 -07003368// This should only be called from the main thread. Otherwise it would need
3369// the lock and should use mCurrentState rather than mDrawingState.
3370void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003371 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003372 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003373 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003374
3375 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3376}
3377
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003378void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003379{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003380 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003381 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3382
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003383 if (isLayerTripleBufferingDisabled())
3384 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003385
3386 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003387 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003388 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003389 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003390 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3391 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003392 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003393}
3394
Dan Stozab90cf072015-03-05 11:05:59 -08003395void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3396{
3397 result.appendFormat("Static screen stats:\n");
3398 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3399 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3400 float percent = 100.0f *
3401 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3402 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3403 b + 1, bucketTimeSec, percent);
3404 }
3405 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3406 float percent = 100.0f *
3407 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3408 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3409 NUM_BUCKETS - 1, bucketTimeSec, percent);
3410}
3411
Dan Stozae77c7662016-05-13 11:37:28 -07003412void SurfaceFlinger::recordBufferingStats(const char* layerName,
3413 std::vector<OccupancyTracker::Segment>&& history) {
3414 Mutex::Autolock lock(mBufferingStatsMutex);
3415 auto& stats = mBufferingStats[layerName];
3416 for (const auto& segment : history) {
3417 if (!segment.usedThirdBuffer) {
3418 stats.twoBufferTime += segment.totalTime;
3419 }
3420 if (segment.occupancyAverage < 1.0f) {
3421 stats.doubleBufferedTime += segment.totalTime;
3422 } else if (segment.occupancyAverage < 2.0f) {
3423 stats.tripleBufferedTime += segment.totalTime;
3424 }
3425 ++stats.numSegments;
3426 stats.totalTime += segment.totalTime;
3427 }
3428}
3429
Brian Andersond6927fb2016-07-23 23:37:30 -07003430void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3431 result.appendFormat("Layer frame timestamps:\n");
3432
3433 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3434 const size_t count = currentLayers.size();
3435 for (size_t i=0 ; i<count ; i++) {
3436 currentLayers[i]->dumpFrameEvents(result);
3437 }
3438}
3439
Dan Stozae77c7662016-05-13 11:37:28 -07003440void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3441 result.append("Buffering stats:\n");
3442 result.append(" [Layer name] <Active time> <Two buffer> "
3443 "<Double buffered> <Triple buffered>\n");
3444 Mutex::Autolock lock(mBufferingStatsMutex);
3445 typedef std::tuple<std::string, float, float, float> BufferTuple;
3446 std::map<float, BufferTuple, std::greater<float>> sorted;
3447 for (const auto& statsPair : mBufferingStats) {
3448 const char* name = statsPair.first.c_str();
3449 const BufferingStats& stats = statsPair.second;
3450 if (stats.numSegments == 0) {
3451 continue;
3452 }
3453 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3454 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3455 stats.totalTime;
3456 float doubleBufferRatio = static_cast<float>(
3457 stats.doubleBufferedTime) / stats.totalTime;
3458 float tripleBufferRatio = static_cast<float>(
3459 stats.tripleBufferedTime) / stats.totalTime;
3460 sorted.insert({activeTime, {name, twoBufferRatio,
3461 doubleBufferRatio, tripleBufferRatio}});
3462 }
3463 for (const auto& sortedPair : sorted) {
3464 float activeTime = sortedPair.first;
3465 const BufferTuple& values = sortedPair.second;
3466 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3467 std::get<0>(values).c_str(), activeTime,
3468 std::get<1>(values), std::get<2>(values),
3469 std::get<3>(values));
3470 }
3471 result.append("\n");
3472}
3473
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003474void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3475 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3476
3477 // TODO: print out if wide-color mode is active or not
3478
3479 for (size_t d = 0; d < mDisplays.size(); d++) {
3480 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3481 int32_t hwcId = displayDevice->getHwcDisplayId();
3482 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3483 continue;
3484 }
3485
3486 result.appendFormat("Display %d color modes:\n", hwcId);
3487 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3488 for (auto&& mode : modes) {
3489 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3490 }
3491
3492 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3493 result.appendFormat(" Current color mode: %s (%d)\n",
3494 decodeColorMode(currentMode).c_str(), currentMode);
3495 }
3496 result.append("\n");
3497}
3498
Mathias Agopian74d211a2013-04-22 16:55:35 +02003499void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3500 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003501{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003502 bool colorize = false;
3503 if (index < args.size()
3504 && (args[index] == String16("--color"))) {
3505 colorize = true;
3506 index++;
3507 }
3508
3509 Colorizer colorizer(colorize);
3510
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003511 // figure out if we're stuck somewhere
3512 const nsecs_t now = systemTime();
3513 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3514 const nsecs_t inTransaction(mDebugInTransaction);
3515 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3516 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3517
3518 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003519 * Dump library configuration.
3520 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003521
3522 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003523 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003524 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003525 appendSfConfigString(result);
3526 appendUiConfigString(result);
3527 appendGuiConfigString(result);
3528 result.append("\n");
3529
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003530 result.append("\nWide-Color information:\n");
3531 dumpWideColorInfo(result);
3532
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003533 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003534 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003535 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003536 result.append(SyncFeatures::getInstance().toString());
3537 result.append("\n");
3538
Dan Stoza9e56aa02015-11-02 13:00:03 -08003539 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3540
Andy McFadden41d67d72014-04-25 16:58:34 -07003541 colorizer.bold(result);
3542 result.append("DispSync configuration: ");
3543 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003544 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003545 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003546 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003547 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003548 result.append("\n");
3549
Dan Stozab90cf072015-03-05 11:05:59 -08003550 // Dump static screen stats
3551 result.append("\n");
3552 dumpStaticScreenStats(result);
3553 result.append("\n");
3554
Dan Stozae77c7662016-05-13 11:37:28 -07003555 dumpBufferingStats(result);
3556
Andy McFadden4803b742012-09-24 19:07:20 -07003557 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003558 * Dump the visible layer list
3559 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003560 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003561 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003562 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003563 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003564 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003565 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003566
3567 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003568 * Dump Display state
3569 */
3570
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003571 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003572 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003573 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003574 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3575 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003576 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003577 }
3578
3579 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003580 * Dump SurfaceFlinger global state
3581 */
3582
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003583 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003584 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003585 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003586
Mathias Agopian888c8222012-08-04 21:10:38 -07003587 HWComposer& hwc(getHwComposer());
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07003588 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003589
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003590 colorizer.bold(result);
3591 result.appendFormat("EGL implementation : %s\n",
3592 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3593 colorizer.reset(result);
3594 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003595 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003596
Mathias Agopian875d8e12013-06-07 15:35:48 -07003597 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003598
Mathias Agopian42977342012-08-05 00:40:46 -07003599 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003600 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3601 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003602 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003603 " last eglSwapBuffers() time: %f us\n"
3604 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003605 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003606 " refresh-rate : %f fps\n"
3607 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003608 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003609 " gpu_to_cpu_unsupported : %d\n"
3610 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611 mLastSwapBufferTime/1000.0,
3612 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003613 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003614 1e9 / activeConfig->getVsyncPeriod(),
3615 activeConfig->getDpiX(),
3616 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003617 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003618
Mathias Agopian74d211a2013-04-22 16:55:35 +02003619 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003620 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003621
Mathias Agopian74d211a2013-04-22 16:55:35 +02003622 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003623 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003624
3625 /*
3626 * VSYNC state
3627 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003628 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003629 result.append("\n");
3630
3631 /*
3632 * HWC layer minidump
3633 */
3634 for (size_t d = 0; d < mDisplays.size(); d++) {
3635 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3636 int32_t hwcId = displayDevice->getHwcDisplayId();
3637 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3638 continue;
3639 }
3640
3641 result.appendFormat("Display %d HWC layers:\n", hwcId);
3642 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003643 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003644 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003645 });
Dan Stozae22aec72016-08-01 13:20:59 -07003646 result.append("\n");
3647 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003648
3649 /*
3650 * Dump HWComposer state
3651 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003652 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003653 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003654 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003655 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003656 result.appendFormat(" h/w composer %s\n",
3657 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003658 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003659
3660 /*
3661 * Dump gralloc state
3662 */
3663 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3664 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003665}
3666
Mathias Agopian13127d82013-03-05 17:47:11 -08003667const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003668SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003669 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003670 wp<IBinder> dpy;
3671 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3672 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3673 dpy = mDisplays.keyAt(i);
3674 break;
3675 }
3676 }
3677 if (dpy == NULL) {
3678 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3679 // Just use the primary display so we have something to return
3680 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3681 }
3682 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003683}
3684
Keun young Park63f165f2012-08-31 10:53:36 -07003685bool SurfaceFlinger::startDdmConnection()
3686{
3687 void* libddmconnection_dso =
3688 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3689 if (!libddmconnection_dso) {
3690 return false;
3691 }
3692 void (*DdmConnection_start)(const char* name);
3693 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003694 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003695 if (!DdmConnection_start) {
3696 dlclose(libddmconnection_dso);
3697 return false;
3698 }
3699 (*DdmConnection_start)(getServiceName());
3700 return true;
3701}
3702
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003703status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003704 switch (code) {
3705 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003706 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003707 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003708 case CLEAR_ANIMATION_FRAME_STATS:
3709 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003711 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 {
3713 // codes that require permission check
3714 IPCThreadState* ipc = IPCThreadState::self();
3715 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003716 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003717 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003718 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003719 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003720 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003721 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003722 break;
3723 }
Robert Carr1db73f62016-12-21 12:58:51 -08003724 /*
3725 * Calling setTransactionState is safe, because you need to have been
3726 * granted a reference to Client* and Handle* to do anything with it.
3727 *
3728 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3729 */
3730 case SET_TRANSACTION_STATE:
3731 case CREATE_SCOPED_CONNECTION:
3732 {
3733 return OK;
3734 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003735 case CAPTURE_SCREEN:
3736 {
3737 // codes that require permission check
3738 IPCThreadState* ipc = IPCThreadState::self();
3739 const int pid = ipc->getCallingPid();
3740 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003741 if ((uid != AID_GRAPHICS) &&
3742 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003743 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003744 return PERMISSION_DENIED;
3745 }
3746 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747 }
3748 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003749 return OK;
3750}
3751
3752status_t SurfaceFlinger::onTransact(
3753 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3754{
3755 status_t credentialCheck = CheckTransactCodeCredentials(code);
3756 if (credentialCheck != OK) {
3757 return credentialCheck;
3758 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003759
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003760 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3761 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003762 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003763 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003764 IPCThreadState* ipc = IPCThreadState::self();
3765 const int pid = ipc->getCallingPid();
3766 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003767 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003768 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 return PERMISSION_DENIED;
3770 }
3771 int n;
3772 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003773 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003774 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775 return NO_ERROR;
3776 case 1002: // SHOW_UPDATES
3777 n = data.readInt32();
3778 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003779 invalidateHwcGeometry();
3780 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003781 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003783 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003784 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003785 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003786 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003787 setTransactionFlags(
3788 eTransactionNeeded|
3789 eDisplayTransactionNeeded|
3790 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003791 return NO_ERROR;
3792 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003793 case 1006:{ // send empty update
3794 signalRefresh();
3795 return NO_ERROR;
3796 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003797 case 1008: // toggle use of hw composer
3798 n = data.readInt32();
3799 mDebugDisableHWC = n ? 1 : 0;
3800 invalidateHwcGeometry();
3801 repaintEverything();
3802 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003803 case 1009: // toggle use of transform hint
3804 n = data.readInt32();
3805 mDebugDisableTransformHint = n ? 1 : 0;
3806 invalidateHwcGeometry();
3807 repaintEverything();
3808 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003810 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003811 reply->writeInt32(0);
3812 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003813 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003814 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003815 return NO_ERROR;
3816 case 1013: {
3817 Mutex::Autolock _l(mStateLock);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07003818 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopian42977342012-08-05 00:40:46 -07003819 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003820 return NO_ERROR;
3821 }
3822 case 1014: {
3823 // daltonize
3824 n = data.readInt32();
3825 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003826 case 1:
3827 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3828 break;
3829 case 2:
3830 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3831 break;
3832 case 3:
3833 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3834 break;
3835 default:
3836 mDaltonizer.setType(ColorBlindnessType::None);
3837 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003838 }
3839 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003840 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003841 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003842 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003843 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003844 invalidateHwcGeometry();
3845 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003846 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003848 case 1015: {
3849 // apply a color matrix
3850 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003851 if (n) {
3852 // color matrix is sent as mat3 matrix followed by vec3
3853 // offset, then packed into a mat4 where the last row is
3854 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003855 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003856 for (size_t j = 0; j < 4; j++) {
3857 mColorMatrix[i][j] = data.readFloat();
3858 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003859 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003860 } else {
3861 mColorMatrix = mat4();
3862 }
3863 invalidateHwcGeometry();
3864 repaintEverything();
3865 return NO_ERROR;
3866 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003867 // This is an experimental interface
3868 // Needs to be shifted to proper binder interface when we productize
3869 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003870 n = data.readInt32();
3871 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003872 return NO_ERROR;
3873 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003874 case 1017: {
3875 n = data.readInt32();
3876 mForceFullDamage = static_cast<bool>(n);
3877 return NO_ERROR;
3878 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003879 case 1018: { // Modify Choreographer's phase offset
3880 n = data.readInt32();
3881 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3882 return NO_ERROR;
3883 }
3884 case 1019: { // Modify SurfaceFlinger's phase offset
3885 n = data.readInt32();
3886 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3887 return NO_ERROR;
3888 }
Irvel468051e2016-06-13 16:44:44 -07003889 case 1020: { // Layer updates interceptor
3890 n = data.readInt32();
3891 if (n) {
3892 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003893 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003894 }
3895 else{
3896 ALOGV("Interceptor disabled");
3897 mInterceptor.disable();
3898 }
3899 return NO_ERROR;
3900 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003901 case 1021: { // Disable HWC virtual displays
3902 n = data.readInt32();
3903 mUseHwcVirtualDisplays = !n;
3904 return NO_ERROR;
3905 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 }
3907 }
3908 return err;
3909}
3910
Mathias Agopian53331da2011-08-22 21:44:41 -07003911void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003912 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003913 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003914}
3915
Mathias Agopian59119e62010-10-11 12:37:43 -07003916// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003917// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003918// ---------------------------------------------------------------------------
3919
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003920/* The code below is here to handle b/8734824
3921 *
3922 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003923 * from the surfaceflinger thread to the calling binder thread, where they
3924 * are executed. This allows the calling thread in the calling process to be
3925 * reused and not depend on having "enough" binder threads to handle the
3926 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003927 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003928class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003929 /* Parts of GraphicProducerWrapper are run on two different threads,
3930 * communicating by sending messages via Looper but also by shared member
3931 * data. Coherence maintenance is subtle and in places implicit (ugh).
3932 *
3933 * Don't rely on Looper's sendMessage/handleMessage providing
3934 * release/acquire semantics for any data not actually in the Message.
3935 * Data going from surfaceflinger to binder threads needs to be
3936 * synchronized explicitly.
3937 *
3938 * Barrier open/wait do provide release/acquire semantics. This provides
3939 * implicit synchronization for data coming back from binder to
3940 * surfaceflinger threads.
3941 */
3942
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003943 sp<IGraphicBufferProducer> impl;
3944 sp<Looper> looper;
3945 status_t result;
3946 bool exitPending;
3947 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003948 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003949 uint32_t code;
3950 Parcel const* data;
3951 Parcel* reply;
3952
3953 enum {
3954 MSG_API_CALL,
3955 MSG_EXIT
3956 };
3957
3958 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003959 * Called on surfaceflinger thread. This is called by our "fake"
3960 * BpGraphicBufferProducer. We package the data and reply Parcel and
3961 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003962 */
3963 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003964 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003965 this->code = code;
3966 this->data = &data;
3967 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003968 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003969 // if we've exited, we run the message synchronously right here.
3970 // note (JH): as far as I can tell from looking at the code, this
3971 // never actually happens. if it does, i'm not sure if it happens
3972 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003973 handleMessage(Message(MSG_API_CALL));
3974 } else {
3975 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003976 // Prevent stores to this->{code, data, reply} from being
3977 // reordered later than the construction of Message.
3978 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003979 looper->sendMessage(this, Message(MSG_API_CALL));
3980 barrier.wait();
3981 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003982 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003983 }
3984
3985 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003986 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003987 * call the real BpGraphicBufferProducer.
3988 */
3989 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003990 int what = message.what;
3991 // Prevent reads below from happening before the read from Message
3992 atomic_thread_fence(memory_order_acquire);
3993 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003994 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003995 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003996 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003997 exitRequested = true;
3998 }
3999 }
4000
4001public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004002 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004003 : impl(impl),
4004 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004005 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004006 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004007 exitRequested(false),
4008 code(0),
4009 data(NULL),
4010 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004011 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004012
Jesse Hallb154c422014-07-13 12:47:02 -07004013 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004014 status_t waitForResponse() {
4015 do {
4016 looper->pollOnce(-1);
4017 } while (!exitRequested);
4018 return result;
4019 }
4020
Jesse Hallb154c422014-07-13 12:47:02 -07004021 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004022 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004023 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004024 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004025 // Ensure this->result is visible to the binder thread before it
4026 // handles the message.
4027 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004028 looper->sendMessage(this, Message(MSG_EXIT));
4029 }
4030};
4031
4032
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004033status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4034 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004035 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004036 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004037 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004038
4039 if (CC_UNLIKELY(display == 0))
4040 return BAD_VALUE;
4041
4042 if (CC_UNLIKELY(producer == 0))
4043 return BAD_VALUE;
4044
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004045 // if we have secure windows on this display, never allow the screen capture
4046 // unless the producer interface is local (i.e.: we can take a screenshot for
4047 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004048 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004049
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004050 // Convert to surfaceflinger's internal rotation type.
4051 Transform::orientation_flags rotationFlags;
4052 switch (rotation) {
4053 case ISurfaceComposer::eRotateNone:
4054 rotationFlags = Transform::ROT_0;
4055 break;
4056 case ISurfaceComposer::eRotate90:
4057 rotationFlags = Transform::ROT_90;
4058 break;
4059 case ISurfaceComposer::eRotate180:
4060 rotationFlags = Transform::ROT_180;
4061 break;
4062 case ISurfaceComposer::eRotate270:
4063 rotationFlags = Transform::ROT_270;
4064 break;
4065 default:
4066 rotationFlags = Transform::ROT_0;
4067 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4068 break;
4069 }
4070
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004071 class MessageCaptureScreen : public MessageBase {
4072 SurfaceFlinger* flinger;
4073 sp<IBinder> display;
4074 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004075 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004076 uint32_t reqWidth, reqHeight;
4077 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004078 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004079 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004080 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004081 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004082 public:
4083 MessageCaptureScreen(SurfaceFlinger* flinger,
4084 const sp<IBinder>& display,
4085 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004086 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004087 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004088 bool useIdentityTransform,
4089 Transform::orientation_flags rotation,
4090 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004091 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004092 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004093 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004094 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004095 rotation(rotation), result(PERMISSION_DENIED),
4096 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004097 {
4098 }
4099 status_t getResult() const {
4100 return result;
4101 }
4102 virtual bool handler() {
4103 Mutex::Autolock _l(flinger->mStateLock);
4104 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08004105 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004106 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004107 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004108 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004109 return true;
4110 }
4111 };
4112
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004113 // this creates a "fake" BBinder which will serve as a "fake" remote
4114 // binder to receive the marshaled calls and forward them to the
4115 // real remote (a BpGraphicBufferProducer)
4116 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4117
4118 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4119 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004120 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004122 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004123 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004124
4125 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004126 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004127 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004128 }
4129 return res;
4130}
4131
Mathias Agopian180f10d2013-04-10 22:55:41 -07004132
4133void SurfaceFlinger::renderScreenImplLocked(
4134 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004135 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004136 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004137 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004138{
4139 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004140 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004141
4142 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004143 const int32_t hw_w = hw->getWidth();
4144 const int32_t hw_h = hw->getHeight();
4145 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004146 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004147
Dan Stozac1879002014-05-22 15:59:05 -07004148 // if a default or invalid sourceCrop is passed in, set reasonable values
4149 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4150 !sourceCrop.isValid()) {
4151 sourceCrop.setLeftTop(Point(0, 0));
4152 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4153 }
4154
4155 // ensure that sourceCrop is inside screen
4156 if (sourceCrop.left < 0) {
4157 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4158 }
Dan Stozabe31f442014-06-11 11:20:54 -07004159 if (sourceCrop.right > hw_w) {
4160 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004161 }
4162 if (sourceCrop.top < 0) {
4163 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4164 }
Dan Stozabe31f442014-06-11 11:20:54 -07004165 if (sourceCrop.bottom > hw_h) {
4166 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004167 }
4168
Mathias Agopian180f10d2013-04-10 22:55:41 -07004169 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004170 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004171
4172 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004173 engine.setViewportAndProjection(
4174 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004175 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004176
4177 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004178 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004179
Robert Carr1f0a16a2016-10-24 16:27:39 -07004180 // We loop through the first level of layers without traversing,
4181 // as we need to interpret min/max layer Z in the top level Z space.
4182 for (const auto& layer : mDrawingState.layersSortedByZ) {
4183 if (layer->getLayerStack() != hw->getLayerStack()) {
4184 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004185 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004186 const Layer::State& state(layer->getDrawingState());
4187 if (state.z < minLayerZ || state.z > maxLayerZ) {
4188 continue;
4189 }
4190 layer->traverseInZOrder([&](Layer* layer) {
4191 if (!layer->isVisible()) {
4192 return;
4193 }
4194 if (filtering) layer->setFiltering(true);
4195 layer->draw(hw, useIdentityTransform);
4196 if (filtering) layer->setFiltering(false);
4197 });
4198 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004199
Mathias Agopian931bda12013-08-28 18:11:46 -07004200 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004201}
4202
4203
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004204status_t SurfaceFlinger::captureScreenImplLocked(
4205 const sp<const DisplayDevice>& hw,
4206 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004207 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004208 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004209 bool useIdentityTransform, Transform::orientation_flags rotation,
4210 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004211{
4212 ATRACE_CALL();
4213
Mathias Agopian180f10d2013-04-10 22:55:41 -07004214 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004215 uint32_t hw_w = hw->getWidth();
4216 uint32_t hw_h = hw->getHeight();
4217
4218 if (rotation & Transform::ROT_90) {
4219 std::swap(hw_w, hw_h);
4220 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004221
Mathias Agopian180f10d2013-04-10 22:55:41 -07004222 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4223 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4224 reqWidth, reqHeight, hw_w, hw_h);
4225 return BAD_VALUE;
4226 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004227
Mathias Agopian180f10d2013-04-10 22:55:41 -07004228 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4229 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4230
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004231 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004232 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004233 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004234 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4235 (state.z < minLayerZ || state.z > maxLayerZ)) {
4236 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004237 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004238 layer->traverseInZOrder([&](Layer *layer) {
4239 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4240 layer->isSecure());
4241 });
4242 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004243
4244 if (!isLocalScreenshot && secureLayerIsVisible) {
4245 ALOGW("FB is protected: PERMISSION_DENIED");
4246 return PERMISSION_DENIED;
4247 }
4248
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004249 // create a surface (because we're a producer, and we need to
4250 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004251 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004252
4253 // Put the screenshot Surface into async mode so that
4254 // Layer::headFenceHasSignaled will always return true and we'll latch the
4255 // first buffer regardless of whether or not its acquire fence has
4256 // signaled. This is needed to avoid a race condition in the rotation
4257 // animation. See b/30209608
4258 sur->setAsyncMode(true);
4259
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004260 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004261
Michael Lentine5a16a622015-05-21 13:48:24 -07004262 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4263 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004264 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4265 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004266
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004267 int err = 0;
4268 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004269 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004270 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4271 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004272
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004273 if (err == NO_ERROR) {
4274 ANativeWindowBuffer* buffer;
4275 /* TODO: Once we have the sync framework everywhere this can use
4276 * server-side waits on the fence that dequeueBuffer returns.
4277 */
4278 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4279 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004280 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004281 // create an EGLImage from the buffer so we can later
4282 // turn it into a texture
4283 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4284 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4285 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004286 // this binds the given EGLImage as a framebuffer for the
4287 // duration of this scope.
4288 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4289 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004290 // this will in fact render into our dequeued buffer
4291 // via an FBO, which means we didn't have to create
4292 // an EGLSurface and therefore we're not
4293 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004294 renderScreenImplLocked(
4295 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4296 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004297
Riley Andrews86639902014-08-15 12:27:24 -07004298 // Attempt to create a sync khr object that can produce a sync point. If that
4299 // isn't available, create a non-dupable sync object in the fallback path and
4300 // wait on it directly.
4301 EGLSyncKHR sync;
4302 if (!DEBUG_SCREENSHOTS) {
4303 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004304 // native fence fd will not be populated until flush() is done.
4305 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004306 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004307 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004308 }
Riley Andrews86639902014-08-15 12:27:24 -07004309 if (sync != EGL_NO_SYNC_KHR) {
4310 // get the sync fd
4311 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4312 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4313 ALOGW("captureScreen: failed to dup sync khr object");
4314 syncFd = -1;
4315 }
4316 eglDestroySyncKHR(mEGLDisplay, sync);
4317 } else {
4318 // fallback path
4319 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4320 if (sync != EGL_NO_SYNC_KHR) {
4321 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4322 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4323 EGLint eglErr = eglGetError();
4324 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4325 ALOGW("captureScreen: fence wait timed out");
4326 } else {
4327 ALOGW_IF(eglErr != EGL_SUCCESS,
4328 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4329 }
4330 eglDestroySyncKHR(mEGLDisplay, sync);
4331 } else {
4332 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4333 }
4334 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004335 if (DEBUG_SCREENSHOTS) {
4336 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4337 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4338 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4339 hw, minLayerZ, maxLayerZ);
4340 delete [] pixels;
4341 }
4342
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004343 } else {
4344 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4345 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004346 window->cancelBuffer(window, buffer, syncFd);
4347 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004348 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004349 // destroy our image
4350 eglDestroyImageKHR(mEGLDisplay, image);
4351 } else {
4352 result = BAD_VALUE;
4353 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004354 if (buffer) {
4355 // queueBuffer takes ownership of syncFd
4356 result = window->queueBuffer(window, buffer, syncFd);
4357 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004358 }
4359 } else {
4360 result = BAD_VALUE;
4361 }
4362 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4363 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004364
Mathias Agopian74c40c02010-09-29 13:02:36 -07004365 return result;
4366}
4367
Mathias Agopiand5556842013-09-19 17:08:37 -07004368void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004369 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004370 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004371 for (size_t y=0 ; y<h ; y++) {
4372 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4373 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004374 if (p[x] != 0xFF000000) return;
4375 }
4376 }
4377 ALOGE("*** we just took a black screenshot ***\n"
4378 "requested minz=%d, maxz=%d, layerStack=%d",
4379 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004380
Robert Carr2047fae2016-11-28 14:09:09 -08004381 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004382 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004383 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004384 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4385 state.z <= maxLayerZ) {
4386 layer->traverseInZOrder([&](Layer* layer) {
4387 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4388 layer->isVisible() ? '+' : '-',
4389 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004390 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004391 i++;
4392 });
4393 }
4394 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004395 }
4396}
4397
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004398// ---------------------------------------------------------------------------
4399
Robert Carr2047fae2016-11-28 14:09:09 -08004400void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4401 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004402}
4403
Robert Carr2047fae2016-11-28 14:09:09 -08004404void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4405 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004406}
4407
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004408}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004409
4410
4411#if defined(__gl_h_)
4412#error "don't include gl/gl.h in this file"
4413#endif
4414
4415#if defined(__gl2_h_)
4416#error "don't include gl2/gl2.h in this file"
4417#endif