blob: 61ceda423f4fb046a0cf060e3772bfacb89748ae [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Romain Guyf8b4ca52017-03-16 18:39:20 +000048#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800121bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800122int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600123bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700126 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700128 mTransactionPending(false),
129 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700131 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700132 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800133 mHwc(nullptr),
134 mRealHwc(nullptr),
135 mVrHwc(nullptr),
136 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800152 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000153 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700154 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700155 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700160 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 mNumLayers(0),
162 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
Steven Thomas050b2c82017-03-06 11:45:16 -0800187 // Vr flinger is only enabled on Daydream ready devices.
188 useVrFlinger = getBool< ISurfaceFlingerConfigs,
189 &ISurfaceFlingerConfigs::useVrFlinger>(false);
190
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
192 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
193
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600194 hasWideColorDisplay =
195 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 // debugging stuff...
198 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700201 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showupdates", value, "0");
204 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 property_get("debug.sf.ddms", value, "0");
207 mDebugDDMS = atoi(value);
208 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700209 if (!startDdmConnection()) {
210 // start failed, and DDMS debugging not enabled
211 mDebugDDMS = 0;
212 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700213 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700214 ALOGI_IF(mDebugRegion, "showupdates enabled");
215 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700216
217 property_get("debug.sf.disable_backpressure", value, "0");
218 mPropagateBackpressure = !atoi(value);
219 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700220
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800221 property_get("debug.sf.enable_hwc_vds", value, "0");
222 mUseHwcVirtualDisplays = atoi(value);
223 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800225 property_get("ro.sf.disable_triple_buffer", value, "1");
226 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230void SurfaceFlinger::onFirstRef()
231{
232 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235SurfaceFlinger::~SurfaceFlinger()
236{
Mathias Agopiana4912602012-07-12 14:25:33 -0700237 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
238 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
239 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
Romain Guyf8b4ca52017-03-16 18:39:20 +0000343sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
344{
345 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
346 return gba;
347}
348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
Steven Thomas050b2c82017-03-06 11:45:16 -0800366 if (mVrFlinger) {
367 mVrFlinger->OnBootFinished();
368 }
369
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700370 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700371 // formerly we would just kill the process, but we now ask it to exit so it
372 // can choose where to stop the animation.
373 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700374
375 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
376 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
377 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian3f844832013-08-07 21:24:32 -0700380void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 RenderEngine& engine;
383 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
386 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 }
388 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700389 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 return true;
391 }
392 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700393 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700394}
395
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700396class DispSyncSource : public VSyncSource, private DispSync::Callback {
397public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700398 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000399 const char* name) :
400 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700401 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700402 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000403 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
404 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 mDispSync(dispSync),
406 mCallbackMutex(),
407 mCallback(),
408 mVsyncMutex(),
409 mPhaseOffset(phaseOffset),
410 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 virtual ~DispSyncSource() {}
413
414 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700415 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700423 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700424 } else {
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 }
435
436 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700437 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 mCallback = callback;
439 }
440
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700441 virtual void setPhaseOffset(nsecs_t phaseOffset) {
442 Mutex::Autolock lock(mVsyncMutex);
443
444 // Normalize phaseOffset to [0, period)
445 auto period = mDispSync->getPeriod();
446 phaseOffset %= period;
447 if (phaseOffset < 0) {
448 // If we're here, then phaseOffset is in (-period, 0). After this
449 // operation, it will be in (0, period)
450 phaseOffset += period;
451 }
452 mPhaseOffset = phaseOffset;
453
454 // If we're not enabled, we don't need to mess with the listeners
455 if (!mEnabled) {
456 return;
457 }
458
459 // Remove the listener with the old offset
460 status_t err = mDispSync->removeEventListener(
461 static_cast<DispSync::Callback*>(this));
462 if (err != NO_ERROR) {
463 ALOGE("error unregistering vsync callback: %s (%d)",
464 strerror(-err), err);
465 }
466
467 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000468 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700469 static_cast<DispSync::Callback*>(this));
470 if (err != NO_ERROR) {
471 ALOGE("error registering vsync callback: %s (%d)",
472 strerror(-err), err);
473 }
474 }
475
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700476private:
477 virtual void onDispSyncEvent(nsecs_t when) {
478 sp<VSyncSource::Callback> callback;
479 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700480 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 callback = mCallback;
482
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 if (mTraceVsync) {
484 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700485 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487 }
488
489 if (callback != NULL) {
490 callback->onVSyncEvent(when);
491 }
492 }
493
Tim Murray4a4e4a22016-04-19 16:29:23 +0000494 const char* const mName;
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 int mValue;
497
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700499 const String8 mVsyncOnLabel;
500 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mVsyncMutex; // Protects the following
508 nsecs_t mPhaseOffset;
509 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700510};
511
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700512class InjectVSyncSource : public VSyncSource {
513public:
514 InjectVSyncSource() {}
515
516 virtual ~InjectVSyncSource() {}
517
518 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
519 std::lock_guard<std::mutex> lock(mCallbackMutex);
520 mCallback = callback;
521 }
522
523 virtual void onInjectSyncEvent(nsecs_t when) {
524 std::lock_guard<std::mutex> lock(mCallbackMutex);
525 mCallback->onVSyncEvent(when);
526 }
527
528 virtual void setVSyncEnabled(bool) {}
529 virtual void setPhaseOffset(nsecs_t) {}
530
531private:
532 std::mutex mCallbackMutex; // Protects the following
533 sp<VSyncSource::Callback> mCallback;
534};
535
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700536void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700537 ALOGI( "SurfaceFlinger's main thread ready to run. "
538 "Initializing graphics H/W...");
539
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900540 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
541
Dan Stoza9e56aa02015-11-02 13:00:03 -0800542 { // Autolock scope
543 Mutex::Autolock _l(mStateLock);
544
545 // initialize EGL for the default display
546 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
547 eglInitialize(mEGLDisplay, NULL, NULL);
548
549 // start the EventThread
550 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700552 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700555 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 mEventQueue.setEventThread(mSFEventThread);
557
Tim Murrayacff43d2016-07-29 13:57:24 -0700558 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700559 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700560 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700561 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
563 }
564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
567 HAL_PIXEL_FORMAT_RGBA_8888);
568 }
569
570 // Drop the state lock while we initialize the hardware composer. We drop
571 // the lock because on creation, it will call back into SurfaceFlinger to
572 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800573 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
574 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800575 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800576 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
578
Jesse Hall692c7232012-11-08 15:41:56 -0800579 Mutex::Autolock _l(mStateLock);
580
Ian Elliott5c34de22017-04-10 14:42:30 -0600581 // Inform native graphics APIs whether the present timestamp is supported:
582 if (getHwComposer().hasCapability(
583 HWC2::Capability::PresentFenceIsNotReliable)) {
584 property_set(kTimestampProperty, "0");
585 } else {
586 property_set(kTimestampProperty, "1");
587 }
588
Steven Thomas050b2c82017-03-06 11:45:16 -0800589 if (useVrFlinger) {
590 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
591 mVrFlingerRequestsDisplay = requestDisplay;
592 signalTransaction();
593 };
594 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
595 vrFlingerRequestDisplayCallback);
596 if (!mVrFlinger) {
597 ALOGE("Failed to start vrflinger");
598 }
599 }
600
Mathias Agopian875d8e12013-06-07 15:35:48 -0700601 // retrieve the EGL context that was selected/created
602 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700603
Mathias Agopianda27af92012-09-13 18:17:13 -0700604 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
605 "couldn't create EGLContext");
606
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607 // make the GLContext current so that we can create textures when creating
608 // Layers (which may happens before we render something)
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700609 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700610
Jamie Gennisd1700752013-10-14 12:22:52 -0700611 mEventControlThread = new EventControlThread(this);
612 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
613
Mathias Agopian92a979a2012-08-02 18:32:23 -0700614 // initialize our drawing state
615 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700616
Andy McFadden13a082e2012-08-24 10:16:42 -0700617 // set initial conditions (e.g. unblank default device)
618 initializeDisplays();
619
Dan Stoza4e637772016-07-28 13:31:51 -0700620 mRenderEngine->primeCache();
621
Wei Wangb254fa32017-01-31 17:43:23 -0800622 mStartBootAnimThread = new StartBootAnimThread();
623 if (mStartBootAnimThread->Start() != NO_ERROR) {
624 ALOGE("Run StartBootAnimThread failed!");
625 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800626
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700628}
629
Mathias Agopiana67e4182012-06-19 17:26:12 -0700630void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800631 // Start boot animation service by setting a property mailbox
632 // if property setting thread is already running, Start() will be just a NOP
633 mStartBootAnimThread->Start();
634 // Wait until property was set
635 if (mStartBootAnimThread->join() != NO_ERROR) {
636 ALOGE("Join StartBootAnimThread failed!");
637 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700638}
639
Mathias Agopian875d8e12013-06-07 15:35:48 -0700640size_t SurfaceFlinger::getMaxTextureSize() const {
641 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700642}
643
Mathias Agopian875d8e12013-06-07 15:35:48 -0700644size_t SurfaceFlinger::getMaxViewportDims() const {
645 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700646}
647
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800648// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800649
Jamie Gennis582270d2011-08-17 18:19:00 -0700650bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800651 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800652 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800653 return authenticateSurfaceTextureLocked(bufferProducer);
654}
655
656bool SurfaceFlinger::authenticateSurfaceTextureLocked(
657 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800658 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700659 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800660}
661
Brian Anderson6b376712017-04-04 10:51:39 -0700662status_t SurfaceFlinger::getSupportedFrameTimestamps(
663 std::vector<FrameEvent>* outSupported) const {
664 *outSupported = {
665 FrameEvent::REQUESTED_PRESENT,
666 FrameEvent::ACQUIRE,
667 FrameEvent::LATCH,
668 FrameEvent::FIRST_REFRESH_START,
669 FrameEvent::LAST_REFRESH_START,
670 FrameEvent::GPU_COMPOSITION_DONE,
671 FrameEvent::DEQUEUE_READY,
672 FrameEvent::RELEASE,
673 };
674 if (!getHwComposer().hasCapability(
675 HWC2::Capability::PresentFenceIsNotReliable)) {
676 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
677 }
678 return NO_ERROR;
679}
680
Dan Stoza7f7da322014-05-02 15:26:25 -0700681status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
682 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700683 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700684 return BAD_VALUE;
685 }
686
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500687 if (!display.get())
688 return NAME_NOT_FOUND;
689
Jesse Hall692c7232012-11-08 15:41:56 -0800690 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700691 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800692 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700693 type = i;
694 break;
695 }
696 }
697
698 if (type < 0) {
699 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700700 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700701
Mathias Agopian8b736f12012-08-13 17:54:26 -0700702 // TODO: Not sure if display density should handled by SF any longer
703 class Density {
704 static int getDensityFromProperty(char const* propName) {
705 char property[PROPERTY_VALUE_MAX];
706 int density = 0;
707 if (property_get(propName, property, NULL) > 0) {
708 density = atoi(property);
709 }
710 return density;
711 }
712 public:
713 static int getEmuDensity() {
714 return getDensityFromProperty("qemu.sf.lcd_density"); }
715 static int getBuildDensity() {
716 return getDensityFromProperty("ro.sf.lcd_density"); }
717 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700718
Dan Stoza7f7da322014-05-02 15:26:25 -0700719 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700722 DisplayInfo info = DisplayInfo();
723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 float xdpi = hwConfig->getDpiX();
725 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700726
727 if (type == DisplayDevice::DISPLAY_PRIMARY) {
728 // The density of the device is provided by a build property
729 float density = Density::getBuildDensity() / 160.0f;
730 if (density == 0) {
731 // the build doesn't provide a density -- this is wrong!
732 // use xdpi instead
733 ALOGE("ro.sf.lcd_density must be defined as a build property");
734 density = xdpi / 160.0f;
735 }
736 if (Density::getEmuDensity()) {
737 // if "qemu.sf.lcd_density" is specified, it overrides everything
738 xdpi = ydpi = density = Density::getEmuDensity();
739 density /= 160.0f;
740 }
741 info.density = density;
742
743 // TODO: this needs to go away (currently needed only by webkit)
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700744 {
745 Mutex::Autolock _l(mStateLock);
746 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
747 info.orientation = hw->getOrientation();
748 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 } else {
750 // TODO: where should this value come from?
751 static const int TV_DENSITY = 213;
752 info.density = TV_DENSITY / 160.0f;
753 info.orientation = 0;
754 }
755
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 info.w = hwConfig->getWidth();
757 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700758 info.xdpi = xdpi;
759 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900761 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800762
Andy McFadden91b2ca82014-06-13 14:04:23 -0700763 // This is how far in advance a buffer must be queued for
764 // presentation at a given time. If you want a buffer to appear
765 // on the screen at time N, you must submit the buffer before
766 // (N - presentationDeadline).
767 //
768 // Normally it's one full refresh period (to give SF a chance to
769 // latch the buffer), but this can be reduced by configuring a
770 // DispSync offset. Any additional delays introduced by the hardware
771 // composer or panel must be accounted for here.
772 //
773 // We add an additional 1ms to allow for processing time and
774 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800776 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700777
778 // All non-virtual displays are currently considered secure.
779 info.secure = true;
780
Michael Wright28f24d02016-07-12 13:30:53 -0700781 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700782 }
783
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 return NO_ERROR;
785}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700786
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800787status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700788 DisplayStatInfo* stats) {
789 if (stats == NULL) {
790 return BAD_VALUE;
791 }
792
793 // FIXME for now we always return stats for the primary display
794 memset(stats, 0, sizeof(*stats));
795 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
796 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
797 return NO_ERROR;
798}
799
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700800int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800801 if (display == NULL) {
802 ALOGE("%s : display is NULL", __func__);
803 return BAD_VALUE;
804 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700805
806 Mutex::Autolock _l(mStateLock);
Dan Stoza24a42e92015-03-09 10:04:11 -0700807 sp<DisplayDevice> device(getDisplayDevice(display));
808 if (device != NULL) {
809 return device->getActiveConfig();
810 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700811
Dan Stoza24a42e92015-03-09 10:04:11 -0700812 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700813}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700814
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700815void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
816 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
817 this);
818 int32_t type = hw->getDisplayType();
819 int currentMode = hw->getActiveConfig();
820
821 if (mode == currentMode) {
822 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
823 return;
824 }
825
826 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
827 ALOGW("Trying to set config for virtual display");
828 return;
829 }
830
831 hw->setActiveConfig(mode);
832 getHwComposer().setActiveConfig(type, mode);
833}
834
835status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
836 class MessageSetActiveConfig: public MessageBase {
837 SurfaceFlinger& mFlinger;
838 sp<IBinder> mDisplay;
839 int mMode;
840 public:
841 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
842 int mode) :
843 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
844 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700845 Vector<DisplayInfo> configs;
846 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700847 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700848 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700849 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700850 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700851 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700852 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
853 if (hw == NULL) {
854 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700855 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700856 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
857 ALOGW("Attempt to set active config = %d for virtual display",
858 mMode);
859 } else {
860 mFlinger.setActiveConfigInternal(hw, mMode);
861 }
862 return true;
863 }
864 };
865 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
866 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700867 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700868}
Michael Wright28f24d02016-07-12 13:30:53 -0700869status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
870 Vector<android_color_mode_t>* outColorModes) {
871 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
872 return BAD_VALUE;
873 }
874
875 if (!display.get()) {
876 return NAME_NOT_FOUND;
877 }
878
879 int32_t type = NAME_NOT_FOUND;
880 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
881 if (display == mBuiltinDisplays[i]) {
882 type = i;
883 break;
884 }
885 }
886
887 if (type < 0) {
888 return type;
889 }
890
891 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
892 outColorModes->clear();
893 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
894
895 return NO_ERROR;
896}
897
898android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -0700899 Mutex::Autolock _l(mStateLock);
Michael Wright28f24d02016-07-12 13:30:53 -0700900 sp<DisplayDevice> device(getDisplayDevice(display));
901 if (device != nullptr) {
902 return device->getActiveColorMode();
903 }
904 return static_cast<android_color_mode_t>(BAD_VALUE);
905}
906
907void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
908 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700909 int32_t type = hw->getDisplayType();
910 android_color_mode_t currentMode = hw->getActiveColorMode();
911
912 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700913 return;
914 }
915
916 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
917 ALOGW("Trying to set config for virtual display");
918 return;
919 }
920
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600921 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
922 hw->getDisplayType());
923
Michael Wright28f24d02016-07-12 13:30:53 -0700924 hw->setActiveColorMode(mode);
925 getHwComposer().setActiveColorMode(type, mode);
926}
927
928
929status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
930 android_color_mode_t colorMode) {
931 class MessageSetActiveColorMode: public MessageBase {
932 SurfaceFlinger& mFlinger;
933 sp<IBinder> mDisplay;
934 android_color_mode_t mMode;
935 public:
936 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
937 android_color_mode_t mode) :
938 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
939 virtual bool handler() {
940 Vector<android_color_mode_t> modes;
941 mFlinger.getDisplayColorModes(mDisplay, &modes);
942 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
943 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600944 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
945 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700946 return true;
947 }
948 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
949 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600950 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
951 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700952 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600953 ALOGW("Attempt to set active color mode %s %d for virtual display",
954 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700955 } else {
956 mFlinger.setActiveColorModeInternal(hw, mMode);
957 }
958 return true;
959 }
960 };
961 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
962 postMessageSync(msg);
963 return NO_ERROR;
964}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700965
Svetoslavd85084b2014-03-20 10:28:31 -0700966status_t SurfaceFlinger::clearAnimationFrameStats() {
967 Mutex::Autolock _l(mStateLock);
968 mAnimFrameTracker.clearStats();
969 return NO_ERROR;
970}
971
972status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
973 Mutex::Autolock _l(mStateLock);
974 mAnimFrameTracker.getStats(outStats);
975 return NO_ERROR;
976}
977
Dan Stozac4f471e2016-03-24 09:31:08 -0700978status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
979 HdrCapabilities* outCapabilities) const {
980 Mutex::Autolock _l(mStateLock);
981
982 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
983 if (displayDevice == nullptr) {
984 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
985 return BAD_VALUE;
986 }
987
988 std::unique_ptr<HdrCapabilities> capabilities =
989 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
990 if (capabilities) {
991 std::swap(*outCapabilities, *capabilities);
992 } else {
993 return BAD_VALUE;
994 }
995
996 return NO_ERROR;
997}
998
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700999status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1000 if (enable == mInjectVSyncs) {
1001 return NO_ERROR;
1002 }
1003
1004 if (enable) {
1005 mInjectVSyncs = enable;
1006 ALOGV("VSync Injections enabled");
1007 if (mVSyncInjector.get() == nullptr) {
1008 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001009 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001010 }
1011 mEventQueue.setEventThread(mInjectorEventThread);
1012 } else {
1013 mInjectVSyncs = enable;
1014 ALOGV("VSync Injections disabled");
1015 mEventQueue.setEventThread(mSFEventThread);
1016 mVSyncInjector.clear();
1017 }
1018 return NO_ERROR;
1019}
1020
1021status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1022 if (!mInjectVSyncs) {
1023 ALOGE("VSync Injections not enabled");
1024 return BAD_VALUE;
1025 }
1026 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1027 ALOGV("Injecting VSync inside SurfaceFlinger");
1028 mVSyncInjector->onInjectSyncEvent(when);
1029 }
1030 return NO_ERROR;
1031}
1032
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001033// ----------------------------------------------------------------------------
1034
1035sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001036 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001037}
1038
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001039// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001040
1041void SurfaceFlinger::waitForEvent() {
1042 mEventQueue.waitMessage();
1043}
1044
1045void SurfaceFlinger::signalTransaction() {
1046 mEventQueue.invalidate();
1047}
1048
1049void SurfaceFlinger::signalLayerUpdate() {
1050 mEventQueue.invalidate();
1051}
1052
1053void SurfaceFlinger::signalRefresh() {
1054 mEventQueue.refresh();
1055}
1056
1057status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001058 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001059 return mEventQueue.postMessage(msg, reltime);
1060}
1061
1062status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001063 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001064 status_t res = mEventQueue.postMessage(msg, reltime);
1065 if (res == NO_ERROR) {
1066 msg->wait();
1067 }
1068 return res;
1069}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001070
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001071void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001072 do {
1073 waitForEvent();
1074 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001075}
1076
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077void SurfaceFlinger::enableHardwareVsync() {
1078 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001079 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001081 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1082 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001084 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001085}
1086
Jesse Hall948fe0c2013-10-14 12:56:09 -07001087void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088 Mutex::Autolock _l(mHWVsyncLock);
1089
Jesse Hall948fe0c2013-10-14 12:56:09 -07001090 if (makeAvailable) {
1091 mHWVsyncAvailable = true;
1092 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001093 // Hardware vsync is not currently available, so abort the resync
1094 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001095 return;
1096 }
1097
Dan Stoza9e56aa02015-11-02 13:00:03 -08001098 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1099 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100
1101 mPrimaryDispSync.reset();
1102 mPrimaryDispSync.setPeriod(period);
1103
1104 if (!mPrimaryHWVsyncEnabled) {
1105 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001106 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1107 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108 mPrimaryHWVsyncEnabled = true;
1109 }
1110}
1111
Jesse Hall948fe0c2013-10-14 12:56:09 -07001112void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113 Mutex::Autolock _l(mHWVsyncLock);
1114 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1116 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001117 mPrimaryDispSync.endResync();
1118 mPrimaryHWVsyncEnabled = false;
1119 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001120 if (makeUnavailable) {
1121 mHWVsyncAvailable = false;
1122 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001123}
1124
Tim Murray4a4e4a22016-04-19 16:29:23 +00001125void SurfaceFlinger::resyncWithRateLimit() {
1126 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1127 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001128 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001129 }
1130}
1131
Steven Thomas3cfac282017-02-06 12:29:30 -08001132void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1133 nsecs_t timestamp) {
1134 Mutex::Autolock lock(mStateLock);
1135 // Ignore any vsyncs from the non-active hardware composer.
1136 if (composer != mHwc) {
1137 return;
1138 }
1139
Jamie Gennisd1700752013-10-14 12:22:52 -07001140 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001141
Jamie Gennisd1700752013-10-14 12:22:52 -07001142 { // Scope for the lock
1143 Mutex::Autolock _l(mHWVsyncLock);
1144 if (type == 0 && mPrimaryHWVsyncEnabled) {
1145 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001146 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001147 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001148
1149 if (needsHwVsync) {
1150 enableHardwareVsync();
1151 } else {
1152 disableHardwareVsync(false);
1153 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001154}
1155
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001156void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001157 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001158 *compositorTiming = mCompositorTiming;
1159}
1160
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001161void SurfaceFlinger::createDefaultDisplayDevice() {
1162 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1163 wp<IBinder> token = mBuiltinDisplays[type];
1164
1165 // All non-virtual displays are currently considered secure.
1166 const bool isSecure = true;
1167
1168 sp<IGraphicBufferProducer> producer;
1169 sp<IGraphicBufferConsumer> consumer;
1170 BufferQueue::createBufferQueue(&producer, &consumer, new GraphicBufferAlloc());
1171
1172 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1173
1174 bool hasWideColorModes = false;
1175 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(
1176 type);
1177 for (android_color_mode_t colorMode : modes) {
1178 switch (colorMode) {
1179 case HAL_COLOR_MODE_DISPLAY_P3:
1180 case HAL_COLOR_MODE_ADOBE_RGB:
1181 case HAL_COLOR_MODE_DCI_P3:
1182 hasWideColorModes = true;
1183 break;
1184 default:
1185 break;
1186 }
1187 }
1188 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1189 token, fbs, producer, mRenderEngine->getEGLConfig(),
1190 hasWideColorModes && hasWideColorDisplay);
1191 mDisplays.add(token, hw);
1192 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1193 if (hasWideColorModes && hasWideColorDisplay) {
1194 defaultColorMode = HAL_COLOR_MODE_SRGB;
1195 }
1196 setActiveColorModeInternal(hw, defaultColorMode);
1197}
1198
1199void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001201
1202 if (composer->isUsingVrComposer()) {
1203 // We handle initializing the primary display device for the VR
1204 // window manager hwc explicitly at the time of transition.
1205 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1206 ALOGE("External displays are not supported by the vr hardware composer.");
1207 }
1208 return;
1209 }
1210
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1212 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001213 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1214 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001215 } else {
1216 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001217 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001218 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001220 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001221 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1222 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001223 }
1224 setTransactionFlags(eDisplayTransactionNeeded);
1225
Andy McFadden9e9689c2012-10-10 18:17:51 -07001226 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001227 }
Mathias Agopian86303202012-07-24 22:46:10 -07001228}
1229
Steven Thomas3cfac282017-02-06 12:29:30 -08001230void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1231 Mutex::Autolock lock(mStateLock);
1232 if (composer == mHwc) {
1233 repaintEverything();
1234 } else {
1235 // This isn't from our current hardware composer. If it's a callback
1236 // from the real composer, forward the refresh request to vr
1237 // flinger. Otherwise ignore it.
1238 if (!composer->isUsingVrComposer()) {
1239 mVrFlinger->OnHardwareComposerRefresh();
1240 }
1241 }
1242}
1243
Dan Stoza9e56aa02015-11-02 13:00:03 -08001244void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001245 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001246 getHwComposer().setVsyncEnabled(disp,
1247 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001248}
1249
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001250void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1251 for (size_t i = 0; i < layers.size(); ++i) {
1252 layers[i]->clearHwcLayers();
1253 }
1254}
1255
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001256// Note: it is assumed the caller holds |mStateLock| when this is called
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001257void SurfaceFlinger::resetHwc() {
1258 disableHardwareVsync(true);
1259 clearHwcLayers(mDrawingState.layersSortedByZ);
1260 clearHwcLayers(mCurrentState.layersSortedByZ);
1261 // Clear the drawing state so that the logic inside of
1262 // handleTransactionLocked will fire. It will determine the delta between
1263 // mCurrentState and mDrawingState and re-apply all changes when we make the
1264 // transition.
1265 mDrawingState.displays.clear();
1266 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001267 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001268}
1269
Steven Thomas050b2c82017-03-06 11:45:16 -08001270void SurfaceFlinger::updateVrFlinger() {
1271 if (!mVrFlinger)
1272 return;
1273 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1274 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001275 return;
1276 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001277
1278 bool vrHwcNewlyInitialized = false;
1279
Steven Thomas050b2c82017-03-06 11:45:16 -08001280 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001281 // Construct new HWComposer without holding any locks.
1282 mVrHwc = new HWComposer(true);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001283 vrHwcNewlyInitialized = true;
Mark Urbanus209beca2017-02-23 11:16:04 -08001284 ALOGV("Vr HWC created");
1285 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001286
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001287 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001288
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001289 if (vrFlingerRequestsDisplay) {
1290 resetHwc();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001291
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001292 mHwc = mVrHwc;
1293 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001295 if (vrHwcNewlyInitialized) {
1296 mVrHwc->setEventHandler(
1297 static_cast<HWComposer::EventHandler*>(this));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001298 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001299 } else {
1300 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001301
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001302 resetHwc();
1303
1304 mHwc = mRealHwc;
1305 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306 }
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001307
1308 mVisibleRegionsDirty = true;
1309 invalidateHwcGeometry();
1310
1311 // Explicitly re-initialize the primary display. This is because some other
1312 // parts of this class rely on the primary display always being available.
1313 createDefaultDisplayDevice();
1314
1315 android_atomic_or(1, &mRepaintEverything);
1316 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001317}
1318
Mathias Agopian4fec8732012-06-29 14:12:52 -07001319void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001320 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001322 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001323 bool frameMissed = !mHadClientComposition &&
1324 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001325 (mPreviousPresentFence->getSignalTime() ==
1326 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001327 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001328 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001329 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001330 signalLayerUpdate();
1331 break;
1332 }
1333
Steven Thomas050b2c82017-03-06 11:45:16 -08001334 // Now that we're going to make it to the handleMessageTransaction()
1335 // call below it's safe to call updateVrFlinger(), which will
1336 // potentially trigger a display handoff.
1337 updateVrFlinger();
1338
Dan Stoza6b9454d2014-11-07 16:00:59 -08001339 bool refreshNeeded = handleMessageTransaction();
1340 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001341 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001342 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001343 // Signal a refresh if a transaction modified the window state,
1344 // a new buffer was latched, or if HWC has requested a full
1345 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001346 signalRefresh();
1347 }
1348 break;
1349 }
1350 case MessageQueue::REFRESH: {
1351 handleMessageRefresh();
1352 break;
1353 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354 }
1355}
1356
Dan Stoza6b9454d2014-11-07 16:00:59 -08001357bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001358 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001359 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001360 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001361 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001362 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001363 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001364}
1365
Dan Stoza6b9454d2014-11-07 16:00:59 -08001366bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001367 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001369}
1370
1371void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001373
Pablo Ceballos40845df2016-01-25 17:41:15 -08001374 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001375
Brian Andersond6927fb2016-07-23 23:37:30 -07001376 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001377 rebuildLayerStacks();
1378 setUpHWComposer();
1379 doDebugFlashRegions();
1380 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001381 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001382
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001383 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001384
1385 mHadClientComposition = false;
1386 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1387 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1388 mHadClientComposition = mHadClientComposition ||
1389 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1390 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001391
Dan Stoza9e56aa02015-11-02 13:00:03 -08001392 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001394
Mathias Agopiancd60f992012-08-16 16:28:27 -07001395void SurfaceFlinger::doDebugFlashRegions()
1396{
1397 // is debugging enabled
1398 if (CC_LIKELY(!mDebugRegion))
1399 return;
1400
1401 const bool repaintEverything = mRepaintEverything;
1402 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1403 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001404 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001405 // transform the dirty region into this screen's coordinate space
1406 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1407 if (!dirtyRegion.isEmpty()) {
1408 // redraw the whole screen
1409 doComposeSurfaces(hw, Region(hw->bounds()));
1410
1411 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001412 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001413 RenderEngine& engine(getRenderEngine());
1414 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1415
Mathias Agopianda27af92012-09-13 18:17:13 -07001416 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001417 }
1418 }
1419 }
1420
1421 postFramebuffer();
1422
1423 if (mDebugRegion > 1) {
1424 usleep(mDebugRegion * 1000);
1425 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001426
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001428 auto& displayDevice = mDisplays[displayId];
1429 if (!displayDevice->isDisplayOn()) {
1430 continue;
1431 }
1432
1433 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1435 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001436 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437}
1438
Brian Andersond6927fb2016-07-23 23:37:30 -07001439void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001441 ATRACE_CALL();
1442 ALOGV("preComposition");
1443
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001445 mDrawingState.traverseInZOrder([&](Layer* layer) {
1446 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447 needExtraInvalidate = true;
1448 }
Robert Carr2047fae2016-11-28 14:09:09 -08001449 });
1450
Mathias Agopiancd60f992012-08-16 16:28:27 -07001451 if (needExtraInvalidate) {
1452 signalLayerUpdate();
1453 }
1454}
1455
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001456void SurfaceFlinger::updateCompositorTiming(
1457 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1458 std::shared_ptr<FenceTime>& presentFenceTime) {
1459 // Update queue of past composite+present times and determine the
1460 // most recently known composite to present latency.
1461 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1462 nsecs_t compositeToPresentLatency = -1;
1463 while (!mCompositePresentTimes.empty()) {
1464 CompositePresentTime& cpt = mCompositePresentTimes.front();
1465 // Cached values should have been updated before calling this method,
1466 // which helps avoid duplicate syscalls.
1467 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1468 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1469 break;
1470 }
1471 compositeToPresentLatency = displayTime - cpt.composite;
1472 mCompositePresentTimes.pop();
1473 }
1474
1475 // Don't let mCompositePresentTimes grow unbounded, just in case.
1476 while (mCompositePresentTimes.size() > 16) {
1477 mCompositePresentTimes.pop();
1478 }
1479
Brian Andersond0010582017-03-07 13:20:31 -08001480 setCompositorTimingSnapped(
1481 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1482}
1483
1484void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1485 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001486 // Integer division and modulo round toward 0 not -inf, so we need to
1487 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001488 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001489 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1490 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1491
Brian Andersond0010582017-03-07 13:20:31 -08001492 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1493 if (idealLatency <= 0) {
1494 idealLatency = vsyncInterval;
1495 }
1496
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497 // Snap the latency to a value that removes scheduling jitter from the
1498 // composition and present times, which often have >1ms of jitter.
1499 // Reducing jitter is important if an app attempts to extrapolate
1500 // something (such as user input) to an accurate diasplay time.
1501 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1502 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001503 nsecs_t bias = vsyncInterval / 2;
1504 int64_t extraVsyncs =
1505 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1506 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1507 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508
Brian Andersond0010582017-03-07 13:20:31 -08001509 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1511 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001512 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513}
1514
1515void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001517 ATRACE_CALL();
1518 ALOGV("postComposition");
1519
Brian Anderson3546a3f2016-07-14 11:51:14 -07001520 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001521 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001522 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001523 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001524 }
1525
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001526 // |mStateLock| not needed as we are on the main thread
1527 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001528
1529 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1530 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1531 glCompositionDoneFenceTime =
1532 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1533 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1534 } else {
1535 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1536 }
1537 mGlCompositionDoneTimeline.updateSignalTimes();
1538
Brian Anderson4e606e32017-03-16 15:34:57 -07001539 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1540 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1541 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001542 mDisplayTimeline.updateSignalTimes();
1543
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001544 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1545 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1546
1547 // We use the refreshStartTime which might be sampled a little later than
1548 // when we started doing work for this frame, but that should be okay
1549 // since updateCompositorTiming has snapping logic.
1550 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001551 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001552 CompositorTiming compositorTiming;
1553 {
1554 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1555 compositorTiming = mCompositorTiming;
1556 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557
Robert Carr2047fae2016-11-28 14:09:09 -08001558 mDrawingState.traverseInZOrder([&](Layer* layer) {
1559 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001560 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001561 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001562 recordBufferingStats(layer->getName().string(),
1563 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001564 }
Robert Carr2047fae2016-11-28 14:09:09 -08001565 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001566
Brian Anderson4e606e32017-03-16 15:34:57 -07001567 if (presentFence->isValid()) {
1568 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001569 enableHardwareVsync();
1570 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001571 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001572 }
1573 }
1574
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001575 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001576 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001577 enableHardwareVsync();
1578 }
1579 }
1580
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001581 if (mAnimCompositionPending) {
1582 mAnimCompositionPending = false;
1583
Brian Anderson4e606e32017-03-16 15:34:57 -07001584 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001585 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001586 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001587 } else {
1588 // The HWC doesn't support present fences, so use the refresh
1589 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001590 nsecs_t presentTime =
1591 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001592 mAnimFrameTracker.setActualPresentTime(presentTime);
1593 }
1594 mAnimFrameTracker.advanceFrame();
1595 }
Dan Stozab90cf072015-03-05 11:05:59 -08001596
1597 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1598 return;
1599 }
1600
1601 nsecs_t currentTime = systemTime();
1602 if (mHasPoweredOff) {
1603 mHasPoweredOff = false;
1604 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001605 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001607 if (numPeriods < NUM_BUCKETS - 1) {
1608 mFrameBuckets[numPeriods] += elapsedTime;
1609 } else {
1610 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1611 }
1612 mTotalTime += elapsedTime;
1613 }
1614 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001615}
1616
1617void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 ATRACE_CALL();
1619 ALOGV("rebuildLayerStacks");
1620
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001622 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1623 ATRACE_CALL();
1624 mVisibleRegionsDirty = false;
1625 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001626
Jeff Sharkey76488112017-02-27 14:15:18 -07001627 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1628 Region opaqueRegion;
1629 Region dirtyRegion;
1630 Vector<sp<Layer>> layersSortedByZ;
1631 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1632 const Transform& tr(displayDevice->getTransform());
1633 const Rect bounds(displayDevice->getBounds());
1634 if (displayDevice->isDisplayOn()) {
1635 computeVisibleRegions(
1636 displayDevice->getLayerStack(), dirtyRegion,
1637 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001638
Jeff Sharkey76488112017-02-27 14:15:18 -07001639 mDrawingState.traverseInZOrder([&](Layer* layer) {
1640 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1641 Region drawRegion(tr.transform(
1642 layer->visibleNonTransparentRegion));
1643 drawRegion.andSelf(bounds);
1644 if (!drawRegion.isEmpty()) {
1645 layersSortedByZ.add(layer);
1646 } else {
1647 // Clear out the HWC layer if this layer was
1648 // previously visible, but no longer is
1649 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1650 nullptr);
1651 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001652 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001653 // WM changes displayDevice->layerStack upon sleep/awake.
1654 // Here we make sure we delete the HWC layers even if
1655 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001656 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1657 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001658 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001659 });
1660 }
1661 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1662 displayDevice->undefinedRegion.set(bounds);
1663 displayDevice->undefinedRegion.subtractSelf(
1664 tr.transform(opaqueRegion));
1665 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001666 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001667 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001669
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001670// pickColorMode translates a given dataspace into the best available color mode.
1671// Currently only support sRGB and Display-P3.
1672android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1673 switch (dataSpace) {
1674 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1675 // system expects.
1676 case HAL_DATASPACE_UNKNOWN:
1677 case HAL_DATASPACE_SRGB:
1678 case HAL_DATASPACE_V0_SRGB:
1679 return HAL_COLOR_MODE_SRGB;
1680 break;
1681
1682 case HAL_DATASPACE_DISPLAY_P3:
1683 return HAL_COLOR_MODE_DISPLAY_P3;
1684 break;
1685
1686 default:
1687 // TODO (courtneygo): Do we want to assert an error here?
1688 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1689 dataSpace);
1690 return HAL_COLOR_MODE_SRGB;
1691 break;
1692 }
1693}
1694
1695android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1696 // Only support sRGB and Display-P3 right now.
1697 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1698 return HAL_DATASPACE_DISPLAY_P3;
1699 }
1700 return HAL_DATASPACE_V0_SRGB;
1701}
1702
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001704 ATRACE_CALL();
1705 ALOGV("setUpHWComposer");
1706
Jesse Hall028dc8f2013-08-20 16:35:32 -07001707 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001708 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1709 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1710 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1711
1712 // If nothing has changed (!dirty), don't recompose.
1713 // If something changed, but we don't currently have any visible layers,
1714 // and didn't when we last did a composition, then skip it this time.
1715 // The second rule does two things:
1716 // - When all layers are removed from a display, we'll emit one black
1717 // frame, then nothing more until we get new layers.
1718 // - When a display is created with a private layer stack, we won't
1719 // emit any black frames until a layer is added to the layer stack.
1720 bool mustRecompose = dirty && !(empty && wasEmpty);
1721
1722 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1723 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1724 mustRecompose ? "doing" : "skipping",
1725 dirty ? "+" : "-",
1726 empty ? "+" : "-",
1727 wasEmpty ? "+" : "-");
1728
Dan Stoza71433162014-02-04 16:22:36 -08001729 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001730
1731 if (mustRecompose) {
1732 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1733 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001734 }
1735
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 // build the h/w work list
1737 if (CC_UNLIKELY(mGeometryInvalid)) {
1738 mGeometryInvalid = false;
1739 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1740 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1741 const auto hwcId = displayDevice->getHwcDisplayId();
1742 if (hwcId >= 0) {
1743 const Vector<sp<Layer>>& currentLayers(
1744 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001745 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001746 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 if (!layer->hasHwcLayer(hwcId)) {
1748 auto hwcLayer = mHwc->createLayer(hwcId);
1749 if (hwcLayer) {
1750 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1751 } else {
1752 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001754 }
1755 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001756
Robert Carrae060832016-11-28 10:51:00 -08001757 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001758 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001759 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001760 }
1761 }
1762 }
1763 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001764 }
Riley Andrews03414a12014-07-01 14:22:59 -07001765
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001766
1767 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1768
Dan Stoza9e56aa02015-11-02 13:00:03 -08001769 // Set the per-frame data
1770 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1771 auto& displayDevice = mDisplays[displayId];
1772 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001773
Dan Stoza9e56aa02015-11-02 13:00:03 -08001774 if (hwcId < 0) {
1775 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001776 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001777 if (colorMatrix != mPreviousColorMatrix) {
1778 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1779 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1780 "display %zd: %d", displayId, result);
1781 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001782 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1783 layer->setPerFrameData(displayDevice);
1784 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001785
1786 if (hasWideColorDisplay) {
1787 android_color_mode newColorMode;
1788 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1789
1790 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1791 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1792 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1793 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1794 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1795 }
1796 newColorMode = pickColorMode(newDataSpace);
1797
1798 setActiveColorModeInternal(displayDevice, newColorMode);
1799 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 }
1801
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001802 mPreviousColorMatrix = colorMatrix;
1803
Dan Stoza9e56aa02015-11-02 13:00:03 -08001804 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001805 auto& displayDevice = mDisplays[displayId];
1806 if (!displayDevice->isDisplayOn()) {
1807 continue;
1808 }
1809
1810 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1812 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001813 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001815
Mathias Agopiancd60f992012-08-16 16:28:27 -07001816void SurfaceFlinger::doComposition() {
1817 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001818 ALOGV("doComposition");
1819
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001820 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001821 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001822 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001823 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001824 // transform the dirty region into this screen's coordinate space
1825 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001826
1827 // repaint the framebuffer (if needed)
1828 doDisplayComposition(hw, dirtyRegion);
1829
Mathias Agopiancd60f992012-08-16 16:28:27 -07001830 hw->dirtyRegion.clear();
1831 hw->flip(hw->swapRegion);
1832 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001833 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001835 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836}
1837
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001838void SurfaceFlinger::postFramebuffer()
1839{
Mathias Agopian841cde52012-03-01 15:44:37 -08001840 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001842
Mathias Agopiana44b0412011-10-16 18:46:35 -07001843 const nsecs_t now = systemTime();
1844 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001845
Dan Stoza9e56aa02015-11-02 13:00:03 -08001846 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1847 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001848 if (!displayDevice->isDisplayOn()) {
1849 continue;
1850 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001851 const auto hwcId = displayDevice->getHwcDisplayId();
1852 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001853 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001854 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001855 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001856 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1858 sp<Fence> releaseFence = Fence::NO_FENCE;
1859 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1860 releaseFence = displayDevice->getClientTargetAcquireFence();
1861 } else {
1862 auto hwcLayer = layer->getHwcLayer(hwcId);
1863 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001864 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 layer->onLayerDisplayed(releaseFence);
1866 }
1867 if (hwcId >= 0) {
1868 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001869 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001870 }
1871
Mathias Agopiana44b0412011-10-16 18:46:35 -07001872 mLastSwapBufferTime = systemTime() - now;
1873 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001874
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001875 // |mStateLock| not needed as we are on the main thread
1876 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001877 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1878 logFrameStats();
1879 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001880}
1881
Mathias Agopian87baae12012-07-31 12:38:26 -07001882void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001883{
Mathias Agopian841cde52012-03-01 15:44:37 -08001884 ATRACE_CALL();
1885
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001886 // here we keep a copy of the drawing state (that is the state that's
1887 // going to be overwritten by handleTransactionLocked()) outside of
1888 // mStateLock so that the side-effects of the State assignment
1889 // don't happen with mStateLock held (which can cause deadlocks).
1890 State drawingState(mDrawingState);
1891
Mathias Agopianca4d3602011-05-19 15:38:14 -07001892 Mutex::Autolock _l(mStateLock);
1893 const nsecs_t now = systemTime();
1894 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001895
Mathias Agopianca4d3602011-05-19 15:38:14 -07001896 // Here we're guaranteed that some transaction flags are set
1897 // so we can call handleTransactionLocked() unconditionally.
1898 // We call getTransactionFlags(), which will also clear the flags,
1899 // with mStateLock held to guarantee that mCurrentState won't change
1900 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001901
Mathias Agopiane57f2922012-08-09 16:29:12 -07001902 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001903 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001904
Mathias Agopianca4d3602011-05-19 15:38:14 -07001905 mLastTransactionTime = systemTime() - now;
1906 mDebugInTransaction = 0;
1907 invalidateHwcGeometry();
1908 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001909}
1910
Mathias Agopian87baae12012-07-31 12:38:26 -07001911void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001912{
Dan Stoza7dde5992015-05-22 09:51:44 -07001913 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001914 mCurrentState.traverseInZOrder([](Layer* layer) {
1915 layer->notifyAvailableFrames();
1916 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001917
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918 /*
1919 * Traversal of the children
1920 * (perform the transaction for each of them if needed)
1921 */
1922
Mathias Agopian3559b072012-08-15 13:46:03 -07001923 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001924 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001926 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001927
1928 const uint32_t flags = layer->doTransaction(0);
1929 if (flags & Layer::eVisibleRegion)
1930 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001931 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001932 }
1933
1934 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001935 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001936 */
1937
Mathias Agopiane57f2922012-08-09 16:29:12 -07001938 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001939 // here we take advantage of Vector's copy-on-write semantics to
1940 // improve performance by skipping the transaction entirely when
1941 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001942 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1943 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001944 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001945 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001946 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001947 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001948
1949 // find the displays that were removed
1950 // (ie: in drawing state but not in current state)
1951 // also handle displays that changed
1952 // (ie: displays that are in both lists)
1953 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001954 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1955 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001956 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001957 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001958 // Call makeCurrent() on the primary display so we can
1959 // be sure that nothing associated with this display
1960 // is current.
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07001961 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001962 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001963 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1964 if (hw != NULL)
1965 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001966 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001967 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001968 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001969 } else {
1970 ALOGW("trying to remove the main display");
1971 }
1972 } else {
1973 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001974 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001975 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001976 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1977 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001978 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001979 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001980 // recreating the DisplayDevice, so we just remove it
1981 // from the drawing state, so that it get re-added
1982 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001983 sp<DisplayDevice> hw(getDisplayDevice(display));
1984 if (hw != NULL)
1985 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001986 mDisplays.removeItem(display);
1987 mDrawingState.displays.removeItemsAt(i);
1988 dc--; i--;
1989 // at this point we must loop to the next item
1990 continue;
1991 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001992
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001993 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001994 if (disp != NULL) {
1995 if (state.layerStack != draw[i].layerStack) {
1996 disp->setLayerStack(state.layerStack);
1997 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001998 if ((state.orientation != draw[i].orientation)
1999 || (state.viewport != draw[i].viewport)
2000 || (state.frame != draw[i].frame))
2001 {
2002 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002003 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002004 }
Michael Lentine47e45402014-07-18 15:34:25 -07002005 if (state.width != draw[i].width || state.height != draw[i].height) {
2006 disp->setDisplaySize(state.width, state.height);
2007 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002008 }
2009 }
2010 }
2011
2012 // find displays that were added
2013 // (ie: in current state but not in drawing state)
2014 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002015 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002016 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002017
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002018 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002019 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002020 sp<IGraphicBufferProducer> bqProducer;
2021 sp<IGraphicBufferConsumer> bqConsumer;
Romain Guyf8b4ca52017-03-16 18:39:20 +00002022 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
2023 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002024
Dan Stoza9e56aa02015-11-02 13:00:03 -08002025 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002026 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002027 // Virtual displays without a surface are dormant:
2028 // they have external state (layer stack, projection,
2029 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002030 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002031
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002032 // Allow VR composer to use virtual displays.
2033 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002034 int width = 0;
2035 int status = state.surface->query(
2036 NATIVE_WINDOW_WIDTH, &width);
2037 ALOGE_IF(status != NO_ERROR,
2038 "Unable to query width (%d)", status);
2039 int height = 0;
2040 status = state.surface->query(
2041 NATIVE_WINDOW_HEIGHT, &height);
2042 ALOGE_IF(status != NO_ERROR,
2043 "Unable to query height (%d)", status);
2044 int intFormat = 0;
2045 status = state.surface->query(
2046 NATIVE_WINDOW_FORMAT, &intFormat);
2047 ALOGE_IF(status != NO_ERROR,
2048 "Unable to query format (%d)", status);
2049 auto format = static_cast<android_pixel_format_t>(
2050 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002051
Dan Stoza8cf150a2016-08-02 10:27:31 -07002052 mHwc->allocateVirtualDisplay(width, height, &format,
2053 &hwcId);
2054 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055
Dan Stoza5cf424b2016-05-20 14:02:39 -07002056 // TODO: Plumb requested format back up to consumer
2057
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 sp<VirtualDisplaySurface> vds =
2059 new VirtualDisplaySurface(*mHwc,
2060 hwcId, state.surface, bqProducer,
2061 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002062
2063 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002064 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002065 }
2066 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002067 ALOGE_IF(state.surface!=NULL,
2068 "adding a supported display, but rendering "
2069 "surface is provided (%p), ignoring it",
2070 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002071
2072 hwcId = state.type;
2073 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2074 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002075 }
2076
2077 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002078 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002079 sp<DisplayDevice> hw =
2080 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2081 dispSurface, producer,
2082 mRenderEngine->getEGLConfig(),
2083 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002084 hw->setLayerStack(state.layerStack);
2085 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002086 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002087 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002088 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002089 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002090 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002091 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002092 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002093 }
2094 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002096 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002097
Mathias Agopian84300952012-11-21 16:02:13 -08002098 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2099 // The transform hint might have changed for some layers
2100 // (either because a display has changed, or because a layer
2101 // as changed).
2102 //
2103 // Walk through all the layers in currentLayers,
2104 // and update their transform hint.
2105 //
2106 // If a layer is visible only on a single display, then that
2107 // display is used to calculate the hint, otherwise we use the
2108 // default display.
2109 //
2110 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2111 // the hint is set before we acquire a buffer from the surface texture.
2112 //
2113 // NOTE: layer transactions have taken place already, so we use their
2114 // drawing state. However, SurfaceFlinger's own transaction has not
2115 // happened yet, so we must use the current state layer list
2116 // (soon to become the drawing state list).
2117 //
2118 sp<const DisplayDevice> disp;
2119 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002120 bool first = true;
2121 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002122 // NOTE: we rely on the fact that layers are sorted by
2123 // layerStack first (so we don't have to traverse the list
2124 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002125 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002126 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002127 currentlayerStack = layerStack;
2128 // figure out if this layerstack is mirrored
2129 // (more than one display) if so, pick the default display,
2130 // if not, pick the only display it's on.
2131 disp.clear();
2132 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2133 sp<const DisplayDevice> hw(mDisplays[dpy]);
2134 if (hw->getLayerStack() == currentlayerStack) {
2135 if (disp == NULL) {
2136 disp = hw;
2137 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002138 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002139 break;
2140 }
2141 }
2142 }
2143 }
Chet Haase91d25932013-04-11 15:24:55 -07002144 if (disp == NULL) {
2145 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2146 // redraw after transform hint changes. See bug 8508397.
2147
2148 // could be null when this layer is using a layerStack
2149 // that is not visible on any display. Also can occur at
2150 // screen off/on times.
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07002151 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002152 }
Chet Haase91d25932013-04-11 15:24:55 -07002153 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002154
2155 first = false;
2156 });
Mathias Agopian84300952012-11-21 16:02:13 -08002157 }
2158
2159
Mathias Agopian3559b072012-08-15 13:46:03 -07002160 /*
2161 * Perform our own transaction if needed
2162 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002163
2164 if (mLayersAdded) {
2165 mLayersAdded = false;
2166 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002167 mVisibleRegionsDirty = true;
2168 }
2169
2170 // some layers might have been removed, so
2171 // we need to update the regions they're exposing.
2172 if (mLayersRemoved) {
2173 mLayersRemoved = false;
2174 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002175 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002177 // this layer is not visible anymore
2178 // TODO: we could traverse the tree from front to back and
2179 // compute the actual visible region
2180 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002181 Region visibleReg;
2182 visibleReg.set(layer->computeScreenBounds());
2183 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002184 }
Robert Carr2047fae2016-11-28 14:09:09 -08002185 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186 }
2187
2188 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002189
2190 updateCursorAsync();
2191}
2192
2193void SurfaceFlinger::updateCursorAsync()
2194{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2196 auto& displayDevice = mDisplays[displayId];
2197 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002198 continue;
2199 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002200
2201 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2202 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002203 }
2204 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002205}
2206
2207void SurfaceFlinger::commitTransaction()
2208{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002209 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002210 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002211 for (const auto& l : mLayersPendingRemoval) {
2212 recordBufferingStats(l->getName().string(),
2213 l->getOccupancyHistory(true));
2214 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002215 }
2216 mLayersPendingRemoval.clear();
2217 }
2218
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002219 // If this transaction is part of a window animation then the next frame
2220 // we composite should be considered an animation as well.
2221 mAnimCompositionPending = mAnimTransactionPending;
2222
Mathias Agopian4fec8732012-06-29 14:12:52 -07002223 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002224 mDrawingState.traverseInZOrder([](Layer* layer) {
2225 layer->commitChildList();
2226 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002227 mTransactionPending = false;
2228 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230}
2231
Robert Carr2047fae2016-11-28 14:09:09 -08002232void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002233 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234{
Mathias Agopian841cde52012-03-01 15:44:37 -08002235 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 Region aboveOpaqueLayers;
2239 Region aboveCoveredLayers;
2240 Region dirty;
2241
Mathias Agopian87baae12012-07-31 12:38:26 -07002242 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243
Robert Carr2047fae2016-11-28 14:09:09 -08002244 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002245 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002246 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247
Jesse Hall01e29052013-02-19 16:13:35 -08002248 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002249 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002250 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002251
Mathias Agopianab028732010-03-16 16:41:46 -07002252 /*
2253 * opaqueRegion: area of a surface that is fully opaque.
2254 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002256
2257 /*
2258 * visibleRegion: area of a surface that is visible on screen
2259 * and not fully transparent. This is essentially the layer's
2260 * footprint minus the opaque regions above it.
2261 * Areas covered by a translucent surface are considered visible.
2262 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002263 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002264
2265 /*
2266 * coveredRegion: area of a surface that is covered by all
2267 * visible regions above it (which includes the translucent areas).
2268 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002270
Jesse Halla8026d22012-09-25 13:25:04 -07002271 /*
2272 * transparentRegion: area of a surface that is hinted to be completely
2273 * transparent. This is only used to tell when the layer has no visible
2274 * non-transparent regions and can be removed from the layer list. It
2275 * does not affect the visibleRegion of this layer or any layers
2276 * beneath it. The hint may not be correct if apps don't respect the
2277 * SurfaceView restrictions (which, sadly, some don't).
2278 */
2279 Region transparentRegion;
2280
Mathias Agopianab028732010-03-16 16:41:46 -07002281
2282 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002283 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002284 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002285 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002287 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002288 if (!visibleRegion.isEmpty()) {
2289 // Remove the transparent area from the visible region
2290 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002291 if (tr.preserveRects()) {
2292 // transform the transparent region
2293 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002294 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002295 // transformation too complex, can't do the
2296 // transparent region optimization.
2297 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002298 }
Mathias Agopianab028732010-03-16 16:41:46 -07002299 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300
Mathias Agopianab028732010-03-16 16:41:46 -07002301 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002302 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002303 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002304 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2305 // the opaque region is the layer's footprint
2306 opaqueRegion = visibleRegion;
2307 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308 }
2309 }
2310
Mathias Agopianab028732010-03-16 16:41:46 -07002311 // Clip the covered region to the visible region
2312 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2313
2314 // Update aboveCoveredLayers for next (lower) layer
2315 aboveCoveredLayers.orSelf(visibleRegion);
2316
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317 // subtract the opaque region covered by the layers above us
2318 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
2320 // compute this layer's dirty region
2321 if (layer->contentDirty) {
2322 // we need to invalidate the whole region
2323 dirty = visibleRegion;
2324 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002325 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326 layer->contentDirty = false;
2327 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002328 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002329 * the exposed region consists of two components:
2330 * 1) what's VISIBLE now and was COVERED before
2331 * 2) what's EXPOSED now less what was EXPOSED before
2332 *
2333 * note that (1) is conservative, we start with the whole
2334 * visible region but only keep what used to be covered by
2335 * something -- which mean it may have been exposed.
2336 *
2337 * (2) handles areas that were not covered by anything but got
2338 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002339 */
Mathias Agopianab028732010-03-16 16:41:46 -07002340 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002341 const Region oldVisibleRegion = layer->visibleRegion;
2342 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002343 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2344 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 }
2346 dirty.subtractSelf(aboveOpaqueLayers);
2347
2348 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002349 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350
Mathias Agopianab028732010-03-16 16:41:46 -07002351 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002353
Jesse Halla8026d22012-09-25 13:25:04 -07002354 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355 layer->setVisibleRegion(visibleRegion);
2356 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002357 layer->setVisibleNonTransparentRegion(
2358 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002359 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360
Mathias Agopian87baae12012-07-31 12:38:26 -07002361 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362}
2363
Mathias Agopian87baae12012-07-31 12:38:26 -07002364void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2365 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002366 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002367 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2368 if (hw->getLayerStack() == layerStack) {
2369 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002370 }
2371 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002372}
2373
Dan Stoza6b9454d2014-11-07 16:00:59 -08002374bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002376 ALOGV("handlePageFlip");
2377
Brian Andersond6927fb2016-07-23 23:37:30 -07002378 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379
Mathias Agopian4fec8732012-06-29 14:12:52 -07002380 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002381 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002382
2383 // Store the set of layers that need updates. This set must not change as
2384 // buffers are being latched, as this could result in a deadlock.
2385 // Example: Two producers share the same command stream and:
2386 // 1.) Layer 0 is latched
2387 // 2.) Layer 0 gets a new frame
2388 // 2.) Layer 1 gets a new frame
2389 // 3.) Layer 1 is latched.
2390 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2391 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002392 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002393 if (layer->hasQueuedFrame()) {
2394 frameQueued = true;
2395 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002396 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002397 } else {
2398 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002399 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002400 } else {
2401 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002402 }
Robert Carr2047fae2016-11-28 14:09:09 -08002403 });
2404
Dan Stoza9e56aa02015-11-02 13:00:03 -08002405 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002406 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002407 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002408 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002409 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002410
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002411 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002412
2413 // If we will need to wake up at some time in the future to deal with a
2414 // queued frame that shouldn't be displayed during this vsync period, wake
2415 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002416 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002417 signalLayerUpdate();
2418 }
2419
2420 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002421 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422}
2423
Mathias Agopianad456f92011-01-13 17:53:01 -08002424void SurfaceFlinger::invalidateHwcGeometry()
2425{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002427}
2428
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002429
Fabien Sanglard830b8472016-11-30 16:35:58 -08002430void SurfaceFlinger::doDisplayComposition(
2431 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002432 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433{
Dan Stoza71433162014-02-04 16:22:36 -08002434 // We only need to actually compose the display if:
2435 // 1) It is being handled by hardware composer, which may need this to
2436 // keep its virtual display state machine in sync, or
2437 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002438 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002439 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002441 return;
2442 }
2443
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 ALOGV("doDisplayComposition");
2445
Mathias Agopian87baae12012-07-31 12:38:26 -07002446 Region dirtyRegion(inDirtyRegion);
2447
Mathias Agopianb8a55602009-06-26 19:06:36 -07002448 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002449 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Fabien Sanglard830b8472016-11-30 16:35:58 -08002451 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002452 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002453 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2454 // takes a rectangle, we must make sure to update that whole
2455 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002456 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002457 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002458 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002459 // We need to redraw the rectangle that will be updated
2460 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002461 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002462 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002463 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002464 } else {
2465 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002466 dirtyRegion.set(displayDevice->bounds());
2467 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468 }
2469 }
2470
Fabien Sanglard830b8472016-11-30 16:35:58 -08002471 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002473 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002474 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002475
2476 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002477 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478}
2479
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480bool SurfaceFlinger::doComposeSurfaces(
2481 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002482{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002483 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002484
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002486
2487 mat4 oldColorMatrix;
2488 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2489 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2490 if (applyColorMatrix) {
2491 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2492 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2493 }
2494
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2496 if (hasClientComposition) {
2497 ALOGV("hasClientComposition");
2498
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002499#ifdef USE_HWC2
2500 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2501 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2502#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002503 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002504 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002505 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002506 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07002507
2508 // |mStateLock| not needed as we are on the main thread
2509 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002510 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2511 }
2512 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002513 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002514
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002515 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002516 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2517 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002518 // when using overlays, we assume a fully transparent framebuffer
2519 // NOTE: we could reduce how much we need to clear, for instance
2520 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002521 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002522 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002524 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002525 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002527
2528 // we remove the scissor part
2529 // we're left with the letterbox region
2530 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002532
2533 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002535
2536 // but limit it to the dirty region
2537 region.andSelf(dirty);
2538
Mathias Agopianb9494d52012-04-18 02:28:45 -07002539 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002540 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002541 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002543 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002544 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002545
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002547 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002548 // scissor on the main display. It should never be needed
2549 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550 const Rect& bounds(displayDevice->getBounds());
2551 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002552 if (scissor != bounds) {
2553 // scissor doesn't match the screen's dimensions, so we
2554 // need to clear everything outside of it and enable
2555 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002556
Mathias Agopianf45c5102012-10-24 16:29:17 -07002557 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 const uint32_t height = displayDevice->getHeight();
2559 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002560 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002561 }
2562 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002563 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002564
Mathias Agopian85d751c2012-08-29 16:59:24 -07002565 /*
2566 * and then, render the layers targeted at the framebuffer
2567 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002568
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("Rendering client layers");
2570 const Transform& displayTransform = displayDevice->getTransform();
2571 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002572 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 bool firstLayer = true;
2574 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2575 const Region clip(dirty.intersect(
2576 displayTransform.transform(layer->visibleRegion)));
2577 ALOGV("Layer: %s", layer->getName().string());
2578 ALOGV(" Composition type: %s",
2579 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002580 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002581 switch (layer->getCompositionType(hwcId)) {
2582 case HWC2::Composition::Cursor:
2583 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002584 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002586 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2588 layer->isOpaque(state) && (state.alpha == 1.0f)
2589 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002590 // never clear the very first layer since we're
2591 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002592 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002593 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002594 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002595 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 case HWC2::Composition::Client: {
2597 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002598 break;
2599 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002600 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002601 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002602 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 } else {
2604 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002605 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002607 }
2608 } else {
2609 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002611 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002613 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002615 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002616 }
2617 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002618
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002619 if (applyColorMatrix) {
2620 getRenderEngine().setupColorTransform(oldColorMatrix);
2621 }
2622
Mathias Agopianf45c5102012-10-24 16:29:17 -07002623 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002625 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002626}
2627
Fabien Sanglard830b8472016-11-30 16:35:58 -08002628void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2629 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002630 RenderEngine& engine(getRenderEngine());
2631 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632}
2633
Dan Stoza7d89d062015-04-30 13:29:25 -07002634status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002635 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002636 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002637 const sp<Layer>& lbc,
2638 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002639{
Dan Stoza7d89d062015-04-30 13:29:25 -07002640 // add this layer to the current state list
2641 {
2642 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002643 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002644 return NO_MEMORY;
2645 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002646 if (parent == nullptr) {
2647 mCurrentState.layersSortedByZ.add(lbc);
2648 } else {
2649 parent->addChild(lbc);
2650 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002651 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002652 mLayersAdded = true;
2653 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002654 }
2655
Mathias Agopian96f08192010-06-02 23:28:45 -07002656 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002657 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002658
Dan Stoza7d89d062015-04-30 13:29:25 -07002659 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002660}
2661
Robert Carr9524cb32017-02-13 11:32:32 -08002662status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002663 Mutex::Autolock _l(mStateLock);
2664
Robert Carr1f0a16a2016-10-24 16:27:39 -07002665 const auto& p = layer->getParent();
2666 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2667 mCurrentState.layersSortedByZ.remove(layer);
2668
Robert Carr136e2f62017-02-08 17:54:29 -08002669 // As a matter of normal operation, the LayerCleaner will produce a second
2670 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2671 // so we will succeed in promoting it, but it's already been removed
2672 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2673 // otherwise something has gone wrong and we are leaking the layer.
2674 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002675 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2676 layer->getName().string(),
2677 (p != nullptr) ? p->getName().string() : "no-parent");
2678 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002679 } else if (index < 0) {
2680 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002681 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002682
2683 mLayersPendingRemoval.add(layer);
2684 mLayersRemoved = true;
2685 mNumLayers--;
2686 setTransactionFlags(eTransactionNeeded);
2687 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688}
2689
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002690uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002691 return android_atomic_release_load(&mTransactionFlags);
2692}
2693
Mathias Agopian3f844832013-08-07 21:24:32 -07002694uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002695 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2696}
2697
Mathias Agopian3f844832013-08-07 21:24:32 -07002698uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2700 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002701 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702 }
2703 return old;
2704}
2705
Mathias Agopian8b33f032012-07-24 20:43:54 -07002706void SurfaceFlinger::setTransactionState(
2707 const Vector<ComposerState>& state,
2708 const Vector<DisplayState>& displays,
2709 uint32_t flags)
2710{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002711 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002712 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002713 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002714
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002715 if (flags & eAnimation) {
2716 // For window updates that are part of an animation we must wait for
2717 // previous animation "frames" to be handled.
2718 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002719 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002720 if (CC_UNLIKELY(err != NO_ERROR)) {
2721 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002722 // caller after a few seconds.
2723 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2724 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002725 mAnimTransactionPending = false;
2726 break;
2727 }
2728 }
2729 }
2730
Mathias Agopiane57f2922012-08-09 16:29:12 -07002731 size_t count = displays.size();
2732 for (size_t i=0 ; i<count ; i++) {
2733 const DisplayState& s(displays[i]);
2734 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002735 }
2736
Mathias Agopiane57f2922012-08-09 16:29:12 -07002737 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002738 for (size_t i=0 ; i<count ; i++) {
2739 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002740 // Here we need to check that the interface we're given is indeed
2741 // one of our own. A malicious client could give us a NULL
2742 // IInterface, or one of its own or even one of our own but a
2743 // different type. All these situations would cause us to crash.
2744 //
2745 // NOTE: it would be better to use RTTI as we could directly check
2746 // that we have a Client*. however, RTTI is disabled in Android.
2747 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002748 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002749 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002750 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002751 sp<Client> client( static_cast<Client *>(s.client.get()) );
2752 transactionFlags |= setClientStateLocked(client, s.state);
2753 }
2754 }
2755 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002756 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002757
Robert Carr2a7dbb42016-05-24 11:41:28 -07002758 // If a synchronous transaction is explicitly requested without any changes,
2759 // force a transaction anyway. This can be used as a flush mechanism for
2760 // previous async transactions.
2761 if (transactionFlags == 0 && (flags & eSynchronous)) {
2762 transactionFlags = eTransactionNeeded;
2763 }
2764
Mathias Agopian386aa982011-11-07 21:58:03 -08002765 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002766 if (mInterceptor.isEnabled()) {
2767 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2768 }
Irvel468051e2016-06-13 16:44:44 -07002769
Mathias Agopian386aa982011-11-07 21:58:03 -08002770 // this triggers the transaction
2771 setTransactionFlags(transactionFlags);
2772
2773 // if this is a synchronous transaction, wait for it to take effect
2774 // before returning.
2775 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002776 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002777 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002778 if (flags & eAnimation) {
2779 mAnimTransactionPending = true;
2780 }
2781 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002782 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2783 if (CC_UNLIKELY(err != NO_ERROR)) {
2784 // just in case something goes wrong in SF, return to the
2785 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002786 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2787 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002788 break;
2789 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 }
2792}
2793
Mathias Agopiane57f2922012-08-09 16:29:12 -07002794uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2795{
Jesse Hall9a143922012-10-04 16:29:19 -07002796 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2797 if (dpyIdx < 0)
2798 return 0;
2799
Mathias Agopiane57f2922012-08-09 16:29:12 -07002800 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002801 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002802 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002803 const uint32_t what = s.what;
2804 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002805 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002806 disp.surface = s.surface;
2807 flags |= eDisplayTransactionNeeded;
2808 }
2809 }
2810 if (what & DisplayState::eLayerStackChanged) {
2811 if (disp.layerStack != s.layerStack) {
2812 disp.layerStack = s.layerStack;
2813 flags |= eDisplayTransactionNeeded;
2814 }
2815 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002816 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002817 if (disp.orientation != s.orientation) {
2818 disp.orientation = s.orientation;
2819 flags |= eDisplayTransactionNeeded;
2820 }
2821 if (disp.frame != s.frame) {
2822 disp.frame = s.frame;
2823 flags |= eDisplayTransactionNeeded;
2824 }
2825 if (disp.viewport != s.viewport) {
2826 disp.viewport = s.viewport;
2827 flags |= eDisplayTransactionNeeded;
2828 }
2829 }
Michael Lentine47e45402014-07-18 15:34:25 -07002830 if (what & DisplayState::eDisplaySizeChanged) {
2831 if (disp.width != s.width) {
2832 disp.width = s.width;
2833 flags |= eDisplayTransactionNeeded;
2834 }
2835 if (disp.height != s.height) {
2836 disp.height = s.height;
2837 flags |= eDisplayTransactionNeeded;
2838 }
2839 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002840 }
2841 return flags;
2842}
2843
2844uint32_t SurfaceFlinger::setClientStateLocked(
2845 const sp<Client>& client,
2846 const layer_state_t& s)
2847{
2848 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002849 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002850 if (layer != 0) {
2851 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002852 bool geometryAppliesWithResize =
2853 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002854 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002855 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002856 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002857 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002858 }
2859 if (what & layer_state_t::eLayerChanged) {
2860 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002861 const auto& p = layer->getParent();
2862 if (p == nullptr) {
2863 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2864 if (layer->setLayer(s.z) && idx >= 0) {
2865 mCurrentState.layersSortedByZ.removeAt(idx);
2866 mCurrentState.layersSortedByZ.add(layer);
2867 // we need traversal (state changed)
2868 // AND transaction (list changed)
2869 flags |= eTransactionNeeded|eTraversalNeeded;
2870 }
2871 } else {
2872 if (p->setChildLayer(layer, s.z)) {
2873 flags |= eTransactionNeeded|eTraversalNeeded;
2874 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002875 }
2876 }
2877 if (what & layer_state_t::eSizeChanged) {
2878 if (layer->setSize(s.w, s.h)) {
2879 flags |= eTraversalNeeded;
2880 }
2881 }
2882 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002883 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002884 flags |= eTraversalNeeded;
2885 }
2886 if (what & layer_state_t::eMatrixChanged) {
2887 if (layer->setMatrix(s.matrix))
2888 flags |= eTraversalNeeded;
2889 }
2890 if (what & layer_state_t::eTransparentRegionChanged) {
2891 if (layer->setTransparentRegionHint(s.transparentRegion))
2892 flags |= eTraversalNeeded;
2893 }
Dan Stoza23116082015-06-18 14:58:39 -07002894 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 if (layer->setFlags(s.flags, s.mask))
2896 flags |= eTraversalNeeded;
2897 }
2898 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002899 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002900 flags |= eTraversalNeeded;
2901 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002902 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002903 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002904 flags |= eTraversalNeeded;
2905 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002906 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 // We only allow setting layer stacks for top level layers,
2909 // everything else inherits layer stack from its parent.
2910 if (layer->hasParent()) {
2911 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2912 layer->getName().string());
2913 } else if (idx < 0) {
2914 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2915 "that also does not appear in the top level layer list. Something"
2916 " has gone wrong.", layer->getName().string());
2917 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002918 mCurrentState.layersSortedByZ.removeAt(idx);
2919 mCurrentState.layersSortedByZ.add(layer);
2920 // we need traversal (state changed)
2921 // AND transaction (list changed)
2922 flags |= eTransactionNeeded|eTraversalNeeded;
2923 }
2924 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002925 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002926 if (s.barrierHandle != nullptr) {
2927 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2928 } else if (s.barrierGbp != nullptr) {
2929 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2930 if (authenticateSurfaceTextureLocked(gbp)) {
2931 const auto& otherLayer =
2932 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2933 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2934 } else {
2935 ALOGE("Attempt to defer transaction to to an"
2936 " unrecognized GraphicBufferProducer");
2937 }
2938 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002939 // We don't trigger a traversal here because if no other state is
2940 // changed, we don't want this to cause any more work
2941 }
Robert Carr1db73f62016-12-21 12:58:51 -08002942 if (what & layer_state_t::eReparentChildren) {
2943 if (layer->reparentChildren(s.reparentHandle)) {
2944 flags |= eTransactionNeeded|eTraversalNeeded;
2945 }
2946 }
Robert Carr9524cb32017-02-13 11:32:32 -08002947 if (what & layer_state_t::eDetachChildren) {
2948 layer->detachChildren();
2949 }
Robert Carrc3574f72016-03-24 12:19:32 -07002950 if (what & layer_state_t::eOverrideScalingModeChanged) {
2951 layer->setOverrideScalingMode(s.overrideScalingMode);
2952 // We don't trigger a traversal here because if no other state is
2953 // changed, we don't want this to cause any more work
2954 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002955 }
2956 return flags;
2957}
2958
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002959status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002960 const String8& name,
2961 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002962 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002963 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2964 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002966 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002967 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002968 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002969 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002970 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002971
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002972 status_t result = NO_ERROR;
2973
2974 sp<Layer> layer;
2975
Cody Northropbc755282017-03-31 12:00:08 -06002976 String8 uniqueName = getUniqueLayerName(name);
2977
Mathias Agopian3165cc22012-08-08 19:42:09 -07002978 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2979 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002980 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002981 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002982 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002984 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002985 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002986 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002987 handle, gbp, &layer);
2988 break;
2989 default:
2990 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002991 break;
2992 }
2993
Dan Stoza7d89d062015-04-30 13:29:25 -07002994 if (result != NO_ERROR) {
2995 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002997
Albert Chaulk479c60c2017-01-27 14:21:34 -05002998 layer->setInfo(windowType, ownerUid);
2999
Robert Carr1f0a16a2016-10-24 16:27:39 -07003000 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003001 if (result != NO_ERROR) {
3002 return result;
3003 }
Irvelffc9efc2016-07-27 15:16:37 -07003004 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003005
3006 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003007 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008}
3009
Cody Northropbc755282017-03-31 12:00:08 -06003010String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3011{
3012 bool matchFound = true;
3013 uint32_t dupeCounter = 0;
3014
3015 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3016 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3017
3018 // Loop over layers until we're sure there is no matching name
3019 while (matchFound) {
3020 matchFound = false;
3021 mDrawingState.traverseInZOrder([&](Layer* layer) {
3022 if (layer->getName() == uniqueName) {
3023 matchFound = true;
3024 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3025 }
3026 });
3027 }
3028
3029 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3030
3031 return uniqueName;
3032}
3033
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003034status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3035 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3036 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037{
3038 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003039 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 case PIXEL_FORMAT_TRANSPARENT:
3041 case PIXEL_FORMAT_TRANSLUCENT:
3042 format = PIXEL_FORMAT_RGBA_8888;
3043 break;
3044 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003045 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 break;
3047 }
3048
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003049 *outLayer = new Layer(this, client, name, w, h, flags);
3050 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3051 if (err == NO_ERROR) {
3052 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003053 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003055
3056 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3057 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058}
3059
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003060status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3061 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3062 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003064 *outLayer = new LayerDim(this, client, name, w, h, flags);
3065 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003066 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003068}
3069
Mathias Agopianac9fa422013-02-11 16:40:36 -08003070status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071{
Robert Carr9524cb32017-02-13 11:32:32 -08003072 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003073 status_t err = NO_ERROR;
3074 sp<Layer> l(client->getLayerUser(handle));
3075 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003076 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003077 err = removeLayer(l);
3078 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3079 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003080 }
3081 return err;
3082}
3083
Mathias Agopian13127d82013-03-05 17:47:11 -08003084status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003085{
Mathias Agopian67106042013-03-14 19:18:13 -07003086 // called by ~LayerCleaner() when all references to the IBinder (handle)
3087 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003088 sp<Layer> l = layer.promote();
3089 if (l == nullptr) {
3090 // The layer has already been removed, carry on
3091 return NO_ERROR;
3092 } if (l->getParent() != nullptr) {
3093 // If we have a parent, then we can continue to live as long as it does.
3094 return NO_ERROR;
3095 }
3096 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097}
3098
Mathias Agopianb60314a2012-04-10 22:09:54 -07003099// ---------------------------------------------------------------------------
3100
Andy McFadden13a082e2012-08-24 10:16:42 -07003101void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003102 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003103 Vector<ComposerState> state;
3104 Vector<DisplayState> displays;
3105 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003106 d.what = DisplayState::eDisplayProjectionChanged |
3107 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003108 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003109 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003110 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003111 d.frame.makeInvalid();
3112 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003113 d.width = 0;
3114 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003115 displays.add(d);
3116 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003117 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003118
Dan Stoza9e56aa02015-11-02 13:00:03 -08003119 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3120 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003121 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003122
Brian Andersond0010582017-03-07 13:20:31 -08003123 // Use phase of 0 since phase is not known.
3124 // Use latency of 0, which will snap to the ideal latency.
3125 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003126}
3127
3128void SurfaceFlinger::initializeDisplays() {
3129 class MessageScreenInitialized : public MessageBase {
3130 SurfaceFlinger* flinger;
3131 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003132 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003133 virtual bool handler() {
3134 flinger->onInitializeDisplays();
3135 return true;
3136 }
3137 };
3138 sp<MessageBase> msg = new MessageScreenInitialized(this);
3139 postMessageAsync(msg); // we may be called from main thread, use async message
3140}
3141
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003142void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3143 int mode) {
3144 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3145 this);
3146 int32_t type = hw->getDisplayType();
3147 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003148
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003149 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003150 return;
3151 }
3152
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003153 hw->setPowerMode(mode);
3154 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3155 ALOGW("Trying to set power mode for virtual display");
3156 return;
3157 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003158
Irvelffc9efc2016-07-27 15:16:37 -07003159 if (mInterceptor.isEnabled()) {
3160 Mutex::Autolock _l(mStateLock);
3161 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3162 if (idx < 0) {
3163 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3164 return;
3165 }
3166 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3167 }
3168
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003169 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003170 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003171 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003172 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3173 // FIXME: eventthread only knows about the main display right now
3174 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003175 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003176 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003178 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003179 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003180 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003181
3182 struct sched_param param = {0};
3183 param.sched_priority = 1;
3184 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3185 ALOGW("Couldn't set SCHED_FIFO on display on");
3186 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003187 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003188 // Turn off the display
3189 struct sched_param param = {0};
3190 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3191 ALOGW("Couldn't set SCHED_OTHER on display off");
3192 }
3193
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003194 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003195 disableHardwareVsync(true); // also cancels any in-progress resync
3196
Mathias Agopiancde87a32012-09-13 14:09:01 -07003197 // FIXME: eventthread only knows about the main display right now
3198 mEventThread->onScreenReleased();
3199 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003200
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003201 getHwComposer().setPowerMode(type, mode);
3202 mVisibleRegionsDirty = true;
3203 // from this point on, SF will stop drawing on this display
3204 } else {
3205 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003206 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003207}
3208
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003209void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3210 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003211 SurfaceFlinger& mFlinger;
3212 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003214 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003215 MessageSetPowerMode(SurfaceFlinger& flinger,
3216 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3217 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003218 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003219 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003220 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003221 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003222 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003223 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003224 ALOGW("Attempt to set power mode = %d for virtual display",
3225 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003226 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003227 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003228 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003229 return true;
3230 }
3231 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003232 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003233 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003234}
3235
3236// ---------------------------------------------------------------------------
3237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3239{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003241
Mathias Agopianbd115332013-04-18 16:41:04 -07003242 IPCThreadState* ipc = IPCThreadState::self();
3243 const int pid = ipc->getCallingPid();
3244 const int uid = ipc->getCallingUid();
3245 if ((uid != AID_SHELL) &&
3246 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003247 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003248 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003249 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003250 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003251 // (this would indicate SF is stuck, but we want to be able to
3252 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003253 status_t err = mStateLock.timedLock(s2ns(1));
3254 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003255 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003256 result.appendFormat(
3257 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3258 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003259 }
3260
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003261 bool dumpAll = true;
3262 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003263 size_t numArgs = args.size();
3264 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003265 if ((index < numArgs) &&
3266 (args[index] == String16("--list"))) {
3267 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003268 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003269 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003270 }
3271
3272 if ((index < numArgs) &&
3273 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003274 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003275 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003276 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003277 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003278
3279 if ((index < numArgs) &&
3280 (args[index] == String16("--latency-clear"))) {
3281 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003282 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003283 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003284 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003285
3286 if ((index < numArgs) &&
3287 (args[index] == String16("--dispsync"))) {
3288 index++;
3289 mPrimaryDispSync.dump(result);
3290 dumpAll = false;
3291 }
Dan Stozab90cf072015-03-05 11:05:59 -08003292
3293 if ((index < numArgs) &&
3294 (args[index] == String16("--static-screen"))) {
3295 index++;
3296 dumpStaticScreenStats(result);
3297 dumpAll = false;
3298 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003299
3300 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003301 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003302 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003303 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003304 dumpAll = false;
3305 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003306
3307 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3308 index++;
3309 dumpWideColorInfo(result);
3310 dumpAll = false;
3311 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003312 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003313
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003314 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003315 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003316 }
3317
Mathias Agopian9795c422009-08-26 16:36:26 -07003318 if (locked) {
3319 mStateLock.unlock();
3320 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 }
3322 write(fd, result.string(), result.size());
3323 return NO_ERROR;
3324}
3325
Dan Stozac7014012014-02-14 15:03:43 -08003326void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3327 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003328{
Robert Carr2047fae2016-11-28 14:09:09 -08003329 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003330 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003331 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003332}
3333
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003334void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003335 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003336{
3337 String8 name;
3338 if (index < args.size()) {
3339 name = String8(args[index]);
3340 index++;
3341 }
3342
Dan Stoza9e56aa02015-11-02 13:00:03 -08003343 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3344 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003345 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003346
3347 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003348 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003349 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003350 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003351 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003352 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003353 }
Robert Carr2047fae2016-11-28 14:09:09 -08003354 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003355 }
3356}
3357
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003358void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003359 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003360{
3361 String8 name;
3362 if (index < args.size()) {
3363 name = String8(args[index]);
3364 index++;
3365 }
3366
Robert Carr2047fae2016-11-28 14:09:09 -08003367 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003368 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003369 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003370 }
Robert Carr2047fae2016-11-28 14:09:09 -08003371 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003372
Svetoslavd85084b2014-03-20 10:28:31 -07003373 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003374}
3375
Jamie Gennis6547ff42013-07-16 20:12:42 -07003376// This should only be called from the main thread. Otherwise it would need
3377// the lock and should use mCurrentState rather than mDrawingState.
3378void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003379 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003380 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003381 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003382
3383 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3384}
3385
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003386void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003387{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003388 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003389 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3390
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003391 if (isLayerTripleBufferingDisabled())
3392 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003393
3394 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003395 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003396 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003397 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003398 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3399 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003400 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003401}
3402
Dan Stozab90cf072015-03-05 11:05:59 -08003403void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3404{
3405 result.appendFormat("Static screen stats:\n");
3406 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3407 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3408 float percent = 100.0f *
3409 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3410 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3411 b + 1, bucketTimeSec, percent);
3412 }
3413 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3414 float percent = 100.0f *
3415 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3416 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3417 NUM_BUCKETS - 1, bucketTimeSec, percent);
3418}
3419
Dan Stozae77c7662016-05-13 11:37:28 -07003420void SurfaceFlinger::recordBufferingStats(const char* layerName,
3421 std::vector<OccupancyTracker::Segment>&& history) {
3422 Mutex::Autolock lock(mBufferingStatsMutex);
3423 auto& stats = mBufferingStats[layerName];
3424 for (const auto& segment : history) {
3425 if (!segment.usedThirdBuffer) {
3426 stats.twoBufferTime += segment.totalTime;
3427 }
3428 if (segment.occupancyAverage < 1.0f) {
3429 stats.doubleBufferedTime += segment.totalTime;
3430 } else if (segment.occupancyAverage < 2.0f) {
3431 stats.tripleBufferedTime += segment.totalTime;
3432 }
3433 ++stats.numSegments;
3434 stats.totalTime += segment.totalTime;
3435 }
3436}
3437
Brian Andersond6927fb2016-07-23 23:37:30 -07003438void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3439 result.appendFormat("Layer frame timestamps:\n");
3440
3441 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3442 const size_t count = currentLayers.size();
3443 for (size_t i=0 ; i<count ; i++) {
3444 currentLayers[i]->dumpFrameEvents(result);
3445 }
3446}
3447
Dan Stozae77c7662016-05-13 11:37:28 -07003448void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3449 result.append("Buffering stats:\n");
3450 result.append(" [Layer name] <Active time> <Two buffer> "
3451 "<Double buffered> <Triple buffered>\n");
3452 Mutex::Autolock lock(mBufferingStatsMutex);
3453 typedef std::tuple<std::string, float, float, float> BufferTuple;
3454 std::map<float, BufferTuple, std::greater<float>> sorted;
3455 for (const auto& statsPair : mBufferingStats) {
3456 const char* name = statsPair.first.c_str();
3457 const BufferingStats& stats = statsPair.second;
3458 if (stats.numSegments == 0) {
3459 continue;
3460 }
3461 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3462 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3463 stats.totalTime;
3464 float doubleBufferRatio = static_cast<float>(
3465 stats.doubleBufferedTime) / stats.totalTime;
3466 float tripleBufferRatio = static_cast<float>(
3467 stats.tripleBufferedTime) / stats.totalTime;
3468 sorted.insert({activeTime, {name, twoBufferRatio,
3469 doubleBufferRatio, tripleBufferRatio}});
3470 }
3471 for (const auto& sortedPair : sorted) {
3472 float activeTime = sortedPair.first;
3473 const BufferTuple& values = sortedPair.second;
3474 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3475 std::get<0>(values).c_str(), activeTime,
3476 std::get<1>(values), std::get<2>(values),
3477 std::get<3>(values));
3478 }
3479 result.append("\n");
3480}
3481
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003482void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3483 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3484
3485 // TODO: print out if wide-color mode is active or not
3486
3487 for (size_t d = 0; d < mDisplays.size(); d++) {
3488 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3489 int32_t hwcId = displayDevice->getHwcDisplayId();
3490 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3491 continue;
3492 }
3493
3494 result.appendFormat("Display %d color modes:\n", hwcId);
3495 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3496 for (auto&& mode : modes) {
3497 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3498 }
3499
3500 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3501 result.appendFormat(" Current color mode: %s (%d)\n",
3502 decodeColorMode(currentMode).c_str(), currentMode);
3503 }
3504 result.append("\n");
3505}
3506
Mathias Agopian74d211a2013-04-22 16:55:35 +02003507void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3508 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003509{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003510 bool colorize = false;
3511 if (index < args.size()
3512 && (args[index] == String16("--color"))) {
3513 colorize = true;
3514 index++;
3515 }
3516
3517 Colorizer colorizer(colorize);
3518
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519 // figure out if we're stuck somewhere
3520 const nsecs_t now = systemTime();
3521 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3522 const nsecs_t inTransaction(mDebugInTransaction);
3523 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3524 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3525
3526 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003527 * Dump library configuration.
3528 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003529
3530 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003531 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003532 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003533 appendSfConfigString(result);
3534 appendUiConfigString(result);
3535 appendGuiConfigString(result);
3536 result.append("\n");
3537
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003538 result.append("\nWide-Color information:\n");
3539 dumpWideColorInfo(result);
3540
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003541 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003542 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003543 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003544 result.append(SyncFeatures::getInstance().toString());
3545 result.append("\n");
3546
Dan Stoza9e56aa02015-11-02 13:00:03 -08003547 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3548
Andy McFadden41d67d72014-04-25 16:58:34 -07003549 colorizer.bold(result);
3550 result.append("DispSync configuration: ");
3551 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003552 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003553 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003554 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003555 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003556 result.append("\n");
3557
Dan Stozab90cf072015-03-05 11:05:59 -08003558 // Dump static screen stats
3559 result.append("\n");
3560 dumpStaticScreenStats(result);
3561 result.append("\n");
3562
Dan Stozae77c7662016-05-13 11:37:28 -07003563 dumpBufferingStats(result);
3564
Andy McFadden4803b742012-09-24 19:07:20 -07003565 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003566 * Dump the visible layer list
3567 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003568 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003569 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003570 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003571 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003572 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003573 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003574
3575 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003576 * Dump Display state
3577 */
3578
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003579 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003580 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003581 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003582 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3583 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003584 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003585 }
3586
3587 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003588 * Dump SurfaceFlinger global state
3589 */
3590
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003591 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003592 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003593 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003594
Mathias Agopian888c8222012-08-04 21:10:38 -07003595 HWComposer& hwc(getHwComposer());
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07003596 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003597
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003598 colorizer.bold(result);
3599 result.appendFormat("EGL implementation : %s\n",
3600 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3601 colorizer.reset(result);
3602 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003603 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003604
Mathias Agopian875d8e12013-06-07 15:35:48 -07003605 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003606
Mathias Agopian42977342012-08-05 00:40:46 -07003607 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003608 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3609 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003610 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611 " last eglSwapBuffers() time: %f us\n"
3612 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003613 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003614 " refresh-rate : %f fps\n"
3615 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003616 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003617 " gpu_to_cpu_unsupported : %d\n"
3618 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003619 mLastSwapBufferTime/1000.0,
3620 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003621 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003622 1e9 / activeConfig->getVsyncPeriod(),
3623 activeConfig->getDpiX(),
3624 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003625 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003626
Mathias Agopian74d211a2013-04-22 16:55:35 +02003627 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003628 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003629
Mathias Agopian74d211a2013-04-22 16:55:35 +02003630 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003631 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003632
3633 /*
3634 * VSYNC state
3635 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003636 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003637 result.append("\n");
3638
3639 /*
3640 * HWC layer minidump
3641 */
3642 for (size_t d = 0; d < mDisplays.size(); d++) {
3643 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3644 int32_t hwcId = displayDevice->getHwcDisplayId();
3645 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3646 continue;
3647 }
3648
3649 result.appendFormat("Display %d HWC layers:\n", hwcId);
3650 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003651 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003652 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003653 });
Dan Stozae22aec72016-08-01 13:20:59 -07003654 result.append("\n");
3655 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003656
3657 /*
3658 * Dump HWComposer state
3659 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003660 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003661 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003662 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003663 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003664 result.appendFormat(" h/w composer %s\n",
3665 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003666 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003667
3668 /*
3669 * Dump gralloc state
3670 */
3671 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3672 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003673}
3674
Mathias Agopian13127d82013-03-05 17:47:11 -08003675const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003676SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003677 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003678 wp<IBinder> dpy;
3679 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3680 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3681 dpy = mDisplays.keyAt(i);
3682 break;
3683 }
3684 }
3685 if (dpy == NULL) {
3686 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3687 // Just use the primary display so we have something to return
3688 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3689 }
3690 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003691}
3692
Keun young Park63f165f2012-08-31 10:53:36 -07003693bool SurfaceFlinger::startDdmConnection()
3694{
3695 void* libddmconnection_dso =
3696 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3697 if (!libddmconnection_dso) {
3698 return false;
3699 }
3700 void (*DdmConnection_start)(const char* name);
3701 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003702 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003703 if (!DdmConnection_start) {
3704 dlclose(libddmconnection_dso);
3705 return false;
3706 }
3707 (*DdmConnection_start)(getServiceName());
3708 return true;
3709}
3710
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003711status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712 switch (code) {
3713 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003714 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003716 case CLEAR_ANIMATION_FRAME_STATS:
3717 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003718 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003719 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 {
3721 // codes that require permission check
3722 IPCThreadState* ipc = IPCThreadState::self();
3723 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003724 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003725 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003726 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003727 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003728 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003730 break;
3731 }
Robert Carr1db73f62016-12-21 12:58:51 -08003732 /*
3733 * Calling setTransactionState is safe, because you need to have been
3734 * granted a reference to Client* and Handle* to do anything with it.
3735 *
3736 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3737 */
3738 case SET_TRANSACTION_STATE:
3739 case CREATE_SCOPED_CONNECTION:
3740 {
3741 return OK;
3742 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003743 case CAPTURE_SCREEN:
3744 {
3745 // codes that require permission check
3746 IPCThreadState* ipc = IPCThreadState::self();
3747 const int pid = ipc->getCallingPid();
3748 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003749 if ((uid != AID_GRAPHICS) &&
3750 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003751 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003752 return PERMISSION_DENIED;
3753 }
3754 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003755 }
3756 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003757 return OK;
3758}
3759
3760status_t SurfaceFlinger::onTransact(
3761 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3762{
3763 status_t credentialCheck = CheckTransactCodeCredentials(code);
3764 if (credentialCheck != OK) {
3765 return credentialCheck;
3766 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003767
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003768 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3769 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003770 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003771 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003772 IPCThreadState* ipc = IPCThreadState::self();
3773 const int pid = ipc->getCallingPid();
3774 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003775 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003776 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 return PERMISSION_DENIED;
3778 }
3779 int n;
3780 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003781 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003782 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003783 return NO_ERROR;
3784 case 1002: // SHOW_UPDATES
3785 n = data.readInt32();
3786 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003787 invalidateHwcGeometry();
3788 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003789 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003790 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003791 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003794 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003795 setTransactionFlags(
3796 eTransactionNeeded|
3797 eDisplayTransactionNeeded|
3798 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003799 return NO_ERROR;
3800 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003801 case 1006:{ // send empty update
3802 signalRefresh();
3803 return NO_ERROR;
3804 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003805 case 1008: // toggle use of hw composer
3806 n = data.readInt32();
3807 mDebugDisableHWC = n ? 1 : 0;
3808 invalidateHwcGeometry();
3809 repaintEverything();
3810 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003811 case 1009: // toggle use of transform hint
3812 n = data.readInt32();
3813 mDebugDisableTransformHint = n ? 1 : 0;
3814 invalidateHwcGeometry();
3815 repaintEverything();
3816 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003818 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003819 reply->writeInt32(0);
3820 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003821 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003822 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 return NO_ERROR;
3824 case 1013: {
3825 Mutex::Autolock _l(mStateLock);
Stephen Kiazyk8d6c16d2017-04-05 16:46:49 -07003826 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopian42977342012-08-05 00:40:46 -07003827 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003828 return NO_ERROR;
3829 }
3830 case 1014: {
3831 // daltonize
3832 n = data.readInt32();
3833 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003834 case 1:
3835 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3836 break;
3837 case 2:
3838 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3839 break;
3840 case 3:
3841 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3842 break;
3843 default:
3844 mDaltonizer.setType(ColorBlindnessType::None);
3845 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003846 }
3847 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003848 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003849 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003850 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003851 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003852 invalidateHwcGeometry();
3853 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003854 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003856 case 1015: {
3857 // apply a color matrix
3858 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003859 if (n) {
3860 // color matrix is sent as mat3 matrix followed by vec3
3861 // offset, then packed into a mat4 where the last row is
3862 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003863 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003864 for (size_t j = 0; j < 4; j++) {
3865 mColorMatrix[i][j] = data.readFloat();
3866 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003867 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003868 } else {
3869 mColorMatrix = mat4();
3870 }
3871 invalidateHwcGeometry();
3872 repaintEverything();
3873 return NO_ERROR;
3874 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003875 // This is an experimental interface
3876 // Needs to be shifted to proper binder interface when we productize
3877 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003878 n = data.readInt32();
3879 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003880 return NO_ERROR;
3881 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003882 case 1017: {
3883 n = data.readInt32();
3884 mForceFullDamage = static_cast<bool>(n);
3885 return NO_ERROR;
3886 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003887 case 1018: { // Modify Choreographer's phase offset
3888 n = data.readInt32();
3889 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3890 return NO_ERROR;
3891 }
3892 case 1019: { // Modify SurfaceFlinger's phase offset
3893 n = data.readInt32();
3894 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3895 return NO_ERROR;
3896 }
Irvel468051e2016-06-13 16:44:44 -07003897 case 1020: { // Layer updates interceptor
3898 n = data.readInt32();
3899 if (n) {
3900 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003901 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003902 }
3903 else{
3904 ALOGV("Interceptor disabled");
3905 mInterceptor.disable();
3906 }
3907 return NO_ERROR;
3908 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003909 case 1021: { // Disable HWC virtual displays
3910 n = data.readInt32();
3911 mUseHwcVirtualDisplays = !n;
3912 return NO_ERROR;
3913 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003914 }
3915 }
3916 return err;
3917}
3918
Mathias Agopian53331da2011-08-22 21:44:41 -07003919void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003920 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003921 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003922}
3923
Mathias Agopian59119e62010-10-11 12:37:43 -07003924// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003925// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003926// ---------------------------------------------------------------------------
3927
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003928/* The code below is here to handle b/8734824
3929 *
3930 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003931 * from the surfaceflinger thread to the calling binder thread, where they
3932 * are executed. This allows the calling thread in the calling process to be
3933 * reused and not depend on having "enough" binder threads to handle the
3934 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003935 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003936class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003937 /* Parts of GraphicProducerWrapper are run on two different threads,
3938 * communicating by sending messages via Looper but also by shared member
3939 * data. Coherence maintenance is subtle and in places implicit (ugh).
3940 *
3941 * Don't rely on Looper's sendMessage/handleMessage providing
3942 * release/acquire semantics for any data not actually in the Message.
3943 * Data going from surfaceflinger to binder threads needs to be
3944 * synchronized explicitly.
3945 *
3946 * Barrier open/wait do provide release/acquire semantics. This provides
3947 * implicit synchronization for data coming back from binder to
3948 * surfaceflinger threads.
3949 */
3950
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003951 sp<IGraphicBufferProducer> impl;
3952 sp<Looper> looper;
3953 status_t result;
3954 bool exitPending;
3955 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003956 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003957 uint32_t code;
3958 Parcel const* data;
3959 Parcel* reply;
3960
3961 enum {
3962 MSG_API_CALL,
3963 MSG_EXIT
3964 };
3965
3966 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003967 * Called on surfaceflinger thread. This is called by our "fake"
3968 * BpGraphicBufferProducer. We package the data and reply Parcel and
3969 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003970 */
3971 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003972 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003973 this->code = code;
3974 this->data = &data;
3975 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003976 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003977 // if we've exited, we run the message synchronously right here.
3978 // note (JH): as far as I can tell from looking at the code, this
3979 // never actually happens. if it does, i'm not sure if it happens
3980 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003981 handleMessage(Message(MSG_API_CALL));
3982 } else {
3983 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003984 // Prevent stores to this->{code, data, reply} from being
3985 // reordered later than the construction of Message.
3986 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003987 looper->sendMessage(this, Message(MSG_API_CALL));
3988 barrier.wait();
3989 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003990 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003991 }
3992
3993 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003994 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003995 * call the real BpGraphicBufferProducer.
3996 */
3997 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003998 int what = message.what;
3999 // Prevent reads below from happening before the read from Message
4000 atomic_thread_fence(memory_order_acquire);
4001 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004002 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004003 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004004 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004005 exitRequested = true;
4006 }
4007 }
4008
4009public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004010 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004011 : impl(impl),
4012 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004013 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004014 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004015 exitRequested(false),
4016 code(0),
4017 data(NULL),
4018 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004019 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004020
Jesse Hallb154c422014-07-13 12:47:02 -07004021 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004022 status_t waitForResponse() {
4023 do {
4024 looper->pollOnce(-1);
4025 } while (!exitRequested);
4026 return result;
4027 }
4028
Jesse Hallb154c422014-07-13 12:47:02 -07004029 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004030 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004031 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004032 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004033 // Ensure this->result is visible to the binder thread before it
4034 // handles the message.
4035 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004036 looper->sendMessage(this, Message(MSG_EXIT));
4037 }
4038};
4039
4040
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004041status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4042 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004043 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004044 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004045 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004046
4047 if (CC_UNLIKELY(display == 0))
4048 return BAD_VALUE;
4049
4050 if (CC_UNLIKELY(producer == 0))
4051 return BAD_VALUE;
4052
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004053 // if we have secure windows on this display, never allow the screen capture
4054 // unless the producer interface is local (i.e.: we can take a screenshot for
4055 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004056 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004057
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004058 // Convert to surfaceflinger's internal rotation type.
4059 Transform::orientation_flags rotationFlags;
4060 switch (rotation) {
4061 case ISurfaceComposer::eRotateNone:
4062 rotationFlags = Transform::ROT_0;
4063 break;
4064 case ISurfaceComposer::eRotate90:
4065 rotationFlags = Transform::ROT_90;
4066 break;
4067 case ISurfaceComposer::eRotate180:
4068 rotationFlags = Transform::ROT_180;
4069 break;
4070 case ISurfaceComposer::eRotate270:
4071 rotationFlags = Transform::ROT_270;
4072 break;
4073 default:
4074 rotationFlags = Transform::ROT_0;
4075 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4076 break;
4077 }
4078
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004079 class MessageCaptureScreen : public MessageBase {
4080 SurfaceFlinger* flinger;
4081 sp<IBinder> display;
4082 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004083 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004084 uint32_t reqWidth, reqHeight;
4085 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004086 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004087 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004088 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004089 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004090 public:
4091 MessageCaptureScreen(SurfaceFlinger* flinger,
4092 const sp<IBinder>& display,
4093 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004094 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004095 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004096 bool useIdentityTransform,
4097 Transform::orientation_flags rotation,
4098 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004099 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004100 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004101 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004102 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004103 rotation(rotation), result(PERMISSION_DENIED),
4104 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004105 {
4106 }
4107 status_t getResult() const {
4108 return result;
4109 }
4110 virtual bool handler() {
4111 Mutex::Autolock _l(flinger->mStateLock);
4112 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08004113 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004114 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004115 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004116 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004117 return true;
4118 }
4119 };
4120
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121 // this creates a "fake" BBinder which will serve as a "fake" remote
4122 // binder to receive the marshaled calls and forward them to the
4123 // real remote (a BpGraphicBufferProducer)
4124 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4125
4126 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4127 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004128 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004129 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004130 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004131 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004132
4133 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004134 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004135 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004136 }
4137 return res;
4138}
4139
Mathias Agopian180f10d2013-04-10 22:55:41 -07004140
4141void SurfaceFlinger::renderScreenImplLocked(
4142 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004143 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004144 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004145 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004146{
4147 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004148 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004149
4150 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004151 const int32_t hw_w = hw->getWidth();
4152 const int32_t hw_h = hw->getHeight();
4153 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004154 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004155
Dan Stozac1879002014-05-22 15:59:05 -07004156 // if a default or invalid sourceCrop is passed in, set reasonable values
4157 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4158 !sourceCrop.isValid()) {
4159 sourceCrop.setLeftTop(Point(0, 0));
4160 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4161 }
4162
4163 // ensure that sourceCrop is inside screen
4164 if (sourceCrop.left < 0) {
4165 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4166 }
Dan Stozabe31f442014-06-11 11:20:54 -07004167 if (sourceCrop.right > hw_w) {
4168 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004169 }
4170 if (sourceCrop.top < 0) {
4171 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4172 }
Dan Stozabe31f442014-06-11 11:20:54 -07004173 if (sourceCrop.bottom > hw_h) {
4174 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004175 }
4176
Mathias Agopian180f10d2013-04-10 22:55:41 -07004177 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004178 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004179
4180 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004181 engine.setViewportAndProjection(
4182 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004183 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004184
4185 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004186 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004187
Robert Carr1f0a16a2016-10-24 16:27:39 -07004188 // We loop through the first level of layers without traversing,
4189 // as we need to interpret min/max layer Z in the top level Z space.
4190 for (const auto& layer : mDrawingState.layersSortedByZ) {
4191 if (layer->getLayerStack() != hw->getLayerStack()) {
4192 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004193 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004194 const Layer::State& state(layer->getDrawingState());
4195 if (state.z < minLayerZ || state.z > maxLayerZ) {
4196 continue;
4197 }
4198 layer->traverseInZOrder([&](Layer* layer) {
4199 if (!layer->isVisible()) {
4200 return;
4201 }
4202 if (filtering) layer->setFiltering(true);
4203 layer->draw(hw, useIdentityTransform);
4204 if (filtering) layer->setFiltering(false);
4205 });
4206 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004207
Mathias Agopian931bda12013-08-28 18:11:46 -07004208 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004209}
4210
4211
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004212status_t SurfaceFlinger::captureScreenImplLocked(
4213 const sp<const DisplayDevice>& hw,
4214 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004215 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004216 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004217 bool useIdentityTransform, Transform::orientation_flags rotation,
4218 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004219{
4220 ATRACE_CALL();
4221
Mathias Agopian180f10d2013-04-10 22:55:41 -07004222 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004223 uint32_t hw_w = hw->getWidth();
4224 uint32_t hw_h = hw->getHeight();
4225
4226 if (rotation & Transform::ROT_90) {
4227 std::swap(hw_w, hw_h);
4228 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004229
Mathias Agopian180f10d2013-04-10 22:55:41 -07004230 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4231 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4232 reqWidth, reqHeight, hw_w, hw_h);
4233 return BAD_VALUE;
4234 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004235
Mathias Agopian180f10d2013-04-10 22:55:41 -07004236 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4237 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4238
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004239 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004240 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004241 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004242 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4243 (state.z < minLayerZ || state.z > maxLayerZ)) {
4244 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004245 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004246 layer->traverseInZOrder([&](Layer *layer) {
4247 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4248 layer->isSecure());
4249 });
4250 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004251
4252 if (!isLocalScreenshot && secureLayerIsVisible) {
4253 ALOGW("FB is protected: PERMISSION_DENIED");
4254 return PERMISSION_DENIED;
4255 }
4256
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004257 // create a surface (because we're a producer, and we need to
4258 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004259 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004260
4261 // Put the screenshot Surface into async mode so that
4262 // Layer::headFenceHasSignaled will always return true and we'll latch the
4263 // first buffer regardless of whether or not its acquire fence has
4264 // signaled. This is needed to avoid a race condition in the rotation
4265 // animation. See b/30209608
4266 sur->setAsyncMode(true);
4267
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004268 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004269
Michael Lentine5a16a622015-05-21 13:48:24 -07004270 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4271 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004272 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4273 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004274
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004275 int err = 0;
4276 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004277 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004278 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4279 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004280
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004281 if (err == NO_ERROR) {
4282 ANativeWindowBuffer* buffer;
4283 /* TODO: Once we have the sync framework everywhere this can use
4284 * server-side waits on the fence that dequeueBuffer returns.
4285 */
4286 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4287 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004288 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004289 // create an EGLImage from the buffer so we can later
4290 // turn it into a texture
4291 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4292 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4293 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004294 // this binds the given EGLImage as a framebuffer for the
4295 // duration of this scope.
4296 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4297 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004298 // this will in fact render into our dequeued buffer
4299 // via an FBO, which means we didn't have to create
4300 // an EGLSurface and therefore we're not
4301 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004302 renderScreenImplLocked(
4303 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4304 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004305
Riley Andrews86639902014-08-15 12:27:24 -07004306 // Attempt to create a sync khr object that can produce a sync point. If that
4307 // isn't available, create a non-dupable sync object in the fallback path and
4308 // wait on it directly.
4309 EGLSyncKHR sync;
4310 if (!DEBUG_SCREENSHOTS) {
4311 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004312 // native fence fd will not be populated until flush() is done.
4313 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004314 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004315 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004316 }
Riley Andrews86639902014-08-15 12:27:24 -07004317 if (sync != EGL_NO_SYNC_KHR) {
4318 // get the sync fd
4319 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4320 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4321 ALOGW("captureScreen: failed to dup sync khr object");
4322 syncFd = -1;
4323 }
4324 eglDestroySyncKHR(mEGLDisplay, sync);
4325 } else {
4326 // fallback path
4327 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4328 if (sync != EGL_NO_SYNC_KHR) {
4329 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4330 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4331 EGLint eglErr = eglGetError();
4332 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4333 ALOGW("captureScreen: fence wait timed out");
4334 } else {
4335 ALOGW_IF(eglErr != EGL_SUCCESS,
4336 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4337 }
4338 eglDestroySyncKHR(mEGLDisplay, sync);
4339 } else {
4340 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4341 }
4342 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004343 if (DEBUG_SCREENSHOTS) {
4344 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4345 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4346 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4347 hw, minLayerZ, maxLayerZ);
4348 delete [] pixels;
4349 }
4350
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004351 } else {
4352 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4353 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004354 window->cancelBuffer(window, buffer, syncFd);
4355 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004356 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004357 // destroy our image
4358 eglDestroyImageKHR(mEGLDisplay, image);
4359 } else {
4360 result = BAD_VALUE;
4361 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004362 if (buffer) {
4363 // queueBuffer takes ownership of syncFd
4364 result = window->queueBuffer(window, buffer, syncFd);
4365 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004366 }
4367 } else {
4368 result = BAD_VALUE;
4369 }
4370 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4371 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004372
Mathias Agopian74c40c02010-09-29 13:02:36 -07004373 return result;
4374}
4375
Mathias Agopiand5556842013-09-19 17:08:37 -07004376void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004377 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004378 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004379 for (size_t y=0 ; y<h ; y++) {
4380 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4381 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004382 if (p[x] != 0xFF000000) return;
4383 }
4384 }
4385 ALOGE("*** we just took a black screenshot ***\n"
4386 "requested minz=%d, maxz=%d, layerStack=%d",
4387 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004388
Robert Carr2047fae2016-11-28 14:09:09 -08004389 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004390 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004391 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004392 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4393 state.z <= maxLayerZ) {
4394 layer->traverseInZOrder([&](Layer* layer) {
4395 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4396 layer->isVisible() ? '+' : '-',
4397 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004398 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004399 i++;
4400 });
4401 }
4402 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004403 }
4404}
4405
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004406// ---------------------------------------------------------------------------
4407
Robert Carr2047fae2016-11-28 14:09:09 -08004408void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4409 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004410}
4411
Robert Carr2047fae2016-11-28 14:09:09 -08004412void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4413 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004414}
4415
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004417
4418
4419#if defined(__gl_h_)
4420#error "don't include gl/gl.h in this file"
4421#endif
4422
4423#if defined(__gl2_h_)
4424#error "don't include gl2/gl2.h in this file"
4425#endif