blob: 71d5cabc9d97b9131d8d0574f9de303fa32e8654 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800118uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800119bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800120bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800121int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600122bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700125 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700127 mTransactionPending(false),
128 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700129 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700130 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700131 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800132 mHwc(nullptr),
133 mRealHwc(nullptr),
134 mVrHwc(nullptr),
135 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800140 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700142 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700143 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700144 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700145 mDebugInSwapBuffers(0),
146 mLastSwapBufferTime(0),
147 mDebugInTransaction(0),
148 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700149 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700150 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800151 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasColorMatrix(false),
156 mHasPoweredOff(false),
157 mFrameBuckets(),
158 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700159 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800160 mNumLayers(0),
161 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800163 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800164
165 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
166 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
167
168 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
169 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
170
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800171 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
172 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700174 useContextPriority = getBool< ISurfaceFlingerConfigs,
175 &ISurfaceFlingerConfigs::useContextPriority>(false);
176
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700177 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
178 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
179
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700180 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
181 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
182
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800183 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
184 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
185
Steven Thomas050b2c82017-03-06 11:45:16 -0800186 // Vr flinger is only enabled on Daydream ready devices.
187 useVrFlinger = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::useVrFlinger>(false);
189
Fabien Sanglard1971b632017-03-10 14:50:03 -0800190 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
192
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600193 hasWideColorDisplay =
194 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 // debugging stuff...
197 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700198
Mathias Agopianb4b17302013-03-20 18:36:41 -0700199 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700200 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 property_get("debug.sf.showupdates", value, "0");
203 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205 property_get("debug.sf.ddms", value, "0");
206 mDebugDDMS = atoi(value);
207 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700208 if (!startDdmConnection()) {
209 // start failed, and DDMS debugging not enabled
210 mDebugDDMS = 0;
211 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700212 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700213 ALOGI_IF(mDebugRegion, "showupdates enabled");
214 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700215
216 property_get("debug.sf.disable_backpressure", value, "0");
217 mPropagateBackpressure = !atoi(value);
218 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700219
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800220 property_get("debug.sf.enable_hwc_vds", value, "0");
221 mUseHwcVirtualDisplays = atoi(value);
222 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800223
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800224 property_get("ro.sf.disable_triple_buffer", value, "1");
225 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800226 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227}
228
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229void SurfaceFlinger::onFirstRef()
230{
231 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800232}
233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234SurfaceFlinger::~SurfaceFlinger()
235{
Mathias Agopiana4912602012-07-12 14:25:33 -0700236 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
237 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
238 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239}
240
Dan Stozac7014012014-02-14 15:03:43 -0800241void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242{
243 // the window manager died on us. prepare its eulogy.
244
Andy McFadden13a082e2012-08-24 10:16:42 -0700245 // restore initial conditions (default device unblank, etc)
246 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247
248 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700249 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250}
251
Robert Carr1db73f62016-12-21 12:58:51 -0800252static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700253 status_t err = client->initCheck();
254 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return nullptr;
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
261 return initClient(new Client(this));
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
265 const sp<IGraphicBufferProducer>& gbp) {
266 if (authenticateSurfaceTexture(gbp) == false) {
267 return nullptr;
268 }
269 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
270 if (layer == nullptr) {
271 return nullptr;
272 }
273
274 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700277sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
278 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279{
280 class DisplayToken : public BBinder {
281 sp<SurfaceFlinger> flinger;
282 virtual ~DisplayToken() {
283 // no more references, this display must be terminated
284 Mutex::Autolock _l(flinger->mStateLock);
285 flinger->mCurrentState.displays.removeItem(this);
286 flinger->setTransactionFlags(eDisplayTransactionNeeded);
287 }
288 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700289 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 : flinger(flinger) {
291 }
292 };
293
294 sp<BBinder> token = new DisplayToken(this);
295
296 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700297 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700298 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 return token;
302}
303
Jesse Hall6c913be2013-08-08 12:15:49 -0700304void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
305 Mutex::Autolock _l(mStateLock);
306
307 ssize_t idx = mCurrentState.displays.indexOfKey(display);
308 if (idx < 0) {
309 ALOGW("destroyDisplay: invalid display token");
310 return;
311 }
312
313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
314 if (!info.isVirtualDisplay()) {
315 ALOGE("destroyDisplay called for non-virtual display");
316 return;
317 }
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700319 mCurrentState.displays.removeItemsAt(idx);
320 setTransactionFlags(eDisplayTransactionNeeded);
321}
322
Jesse Hall692c7232012-11-08 15:41:56 -0800323void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800324 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 ALOGW_IF(mBuiltinDisplays[type],
326 "Overwriting display token for display type %d", type);
327 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800328 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700329 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700331 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800332}
333
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700335 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
337 return NULL;
338 }
Jesse Hall692c7232012-11-08 15:41:56 -0800339 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340}
341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342void SurfaceFlinger::bootFinished()
343{
Wei Wangb254fa32017-01-31 17:43:23 -0800344 if (mStartBootAnimThread->join() != NO_ERROR) {
345 ALOGE("Join StartBootAnimThread failed!");
346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 const nsecs_t now = systemTime();
348 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000349 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700350 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700351
352 // wait patiently for the window manager death
353 const String16 name("window");
354 sp<IBinder> window(defaultServiceManager()->getService(name));
355 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700356 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357 }
358
Steven Thomas050b2c82017-03-06 11:45:16 -0800359 if (mVrFlinger) {
360 mVrFlinger->OnBootFinished();
361 }
362
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 // formerly we would just kill the process, but we now ask it to exit so it
365 // can choose where to stop the animation.
366 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700367
368 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
369 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
370 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371}
372
Mathias Agopian3f844832013-08-07 21:24:32 -0700373void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700374 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 RenderEngine& engine;
376 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700377 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
379 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380 }
381 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383 return true;
384 }
385 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387}
388
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389class DispSyncSource : public VSyncSource, private DispSync::Callback {
390public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700391 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000392 const char* name) :
393 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700394 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700395 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000396 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
397 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 mDispSync(dispSync),
399 mCallbackMutex(),
400 mCallback(),
401 mVsyncMutex(),
402 mPhaseOffset(phaseOffset),
403 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700404
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700405 virtual ~DispSyncSource() {}
406
407 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700408 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000410 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700411 static_cast<DispSync::Callback*>(this));
412 if (err != NO_ERROR) {
413 ALOGE("error registering vsync callback: %s (%d)",
414 strerror(-err), err);
415 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700416 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 } else {
418 status_t err = mDispSync->removeEventListener(
419 static_cast<DispSync::Callback*>(this));
420 if (err != NO_ERROR) {
421 ALOGE("error unregistering vsync callback: %s (%d)",
422 strerror(-err), err);
423 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700424 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700426 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 }
428
429 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 mCallback = callback;
432 }
433
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 virtual void setPhaseOffset(nsecs_t phaseOffset) {
435 Mutex::Autolock lock(mVsyncMutex);
436
437 // Normalize phaseOffset to [0, period)
438 auto period = mDispSync->getPeriod();
439 phaseOffset %= period;
440 if (phaseOffset < 0) {
441 // If we're here, then phaseOffset is in (-period, 0). After this
442 // operation, it will be in (0, period)
443 phaseOffset += period;
444 }
445 mPhaseOffset = phaseOffset;
446
447 // If we're not enabled, we don't need to mess with the listeners
448 if (!mEnabled) {
449 return;
450 }
451
452 // Remove the listener with the old offset
453 status_t err = mDispSync->removeEventListener(
454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error unregistering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
459
460 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000461 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error registering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
467 }
468
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469private:
470 virtual void onDispSyncEvent(nsecs_t when) {
471 sp<VSyncSource::Callback> callback;
472 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 callback = mCallback;
475
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700476 if (mTraceVsync) {
477 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700478 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700479 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 if (callback != NULL) {
483 callback->onVSyncEvent(when);
484 }
485 }
486
Tim Murray4a4e4a22016-04-19 16:29:23 +0000487 const char* const mName;
488
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 int mValue;
490
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700492 const String8 mVsyncOnLabel;
493 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700494
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496
497 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499
500 Mutex mVsyncMutex; // Protects the following
501 nsecs_t mPhaseOffset;
502 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503};
504
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700505class InjectVSyncSource : public VSyncSource {
506public:
507 InjectVSyncSource() {}
508
509 virtual ~InjectVSyncSource() {}
510
511 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
512 std::lock_guard<std::mutex> lock(mCallbackMutex);
513 mCallback = callback;
514 }
515
516 virtual void onInjectSyncEvent(nsecs_t when) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback->onVSyncEvent(when);
519 }
520
521 virtual void setVSyncEnabled(bool) {}
522 virtual void setPhaseOffset(nsecs_t) {}
523
524private:
525 std::mutex mCallbackMutex; // Protects the following
526 sp<VSyncSource::Callback> mCallback;
527};
528
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700530 ALOGI( "SurfaceFlinger's main thread ready to run. "
531 "Initializing graphics H/W...");
532
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900533 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
534
Dan Stoza9e56aa02015-11-02 13:00:03 -0800535 { // Autolock scope
536 Mutex::Autolock _l(mStateLock);
537
538 // initialize EGL for the default display
539 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
540 eglInitialize(mEGLDisplay, NULL, NULL);
541
542 // start the EventThread
543 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
544 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700545 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800546 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
547 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700548 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 mEventQueue.setEventThread(mSFEventThread);
550
Tim Murrayacff43d2016-07-29 13:57:24 -0700551 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700552 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700553 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700554 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
555 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
556 }
557
Dan Stoza9e56aa02015-11-02 13:00:03 -0800558 // Get a RenderEngine for the given display / config (can't fail)
559 mRenderEngine = RenderEngine::create(mEGLDisplay,
560 HAL_PIXEL_FORMAT_RGBA_8888);
561 }
562
563 // Drop the state lock while we initialize the hardware composer. We drop
564 // the lock because on creation, it will call back into SurfaceFlinger to
565 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
567 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800568 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800569 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
571
Jesse Hall692c7232012-11-08 15:41:56 -0800572 Mutex::Autolock _l(mStateLock);
573
Ian Elliott5c34de22017-04-10 14:42:30 -0600574 // Inform native graphics APIs whether the present timestamp is supported:
575 if (getHwComposer().hasCapability(
576 HWC2::Capability::PresentFenceIsNotReliable)) {
577 property_set(kTimestampProperty, "0");
578 } else {
579 property_set(kTimestampProperty, "1");
580 }
581
Steven Thomas050b2c82017-03-06 11:45:16 -0800582 if (useVrFlinger) {
583 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
584 mVrFlingerRequestsDisplay = requestDisplay;
585 signalTransaction();
586 };
587 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
588 vrFlingerRequestDisplayCallback);
589 if (!mVrFlinger) {
590 ALOGE("Failed to start vrflinger");
591 }
592 }
593
Mathias Agopian875d8e12013-06-07 15:35:48 -0700594 // retrieve the EGL context that was selected/created
595 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700596
Mathias Agopianda27af92012-09-13 18:17:13 -0700597 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
598 "couldn't create EGLContext");
599
Dan Stoza9e56aa02015-11-02 13:00:03 -0800600 // make the GLContext current so that we can create textures when creating
601 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700602 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700603
Jamie Gennisd1700752013-10-14 12:22:52 -0700604 mEventControlThread = new EventControlThread(this);
605 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
606
Mathias Agopian92a979a2012-08-02 18:32:23 -0700607 // initialize our drawing state
608 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700609
Andy McFadden13a082e2012-08-24 10:16:42 -0700610 // set initial conditions (e.g. unblank default device)
611 initializeDisplays();
612
Dan Stoza4e637772016-07-28 13:31:51 -0700613 mRenderEngine->primeCache();
614
Wei Wangb254fa32017-01-31 17:43:23 -0800615 mStartBootAnimThread = new StartBootAnimThread();
616 if (mStartBootAnimThread->Start() != NO_ERROR) {
617 ALOGE("Run StartBootAnimThread failed!");
618 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800619
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700621}
622
Mathias Agopiana67e4182012-06-19 17:26:12 -0700623void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800624 // Start boot animation service by setting a property mailbox
625 // if property setting thread is already running, Start() will be just a NOP
626 mStartBootAnimThread->Start();
627 // Wait until property was set
628 if (mStartBootAnimThread->join() != NO_ERROR) {
629 ALOGE("Join StartBootAnimThread failed!");
630 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700631}
632
Mathias Agopian875d8e12013-06-07 15:35:48 -0700633size_t SurfaceFlinger::getMaxTextureSize() const {
634 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700635}
636
Mathias Agopian875d8e12013-06-07 15:35:48 -0700637size_t SurfaceFlinger::getMaxViewportDims() const {
638 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700639}
640
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800641// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800642
Jamie Gennis582270d2011-08-17 18:19:00 -0700643bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800644 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800645 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800646 return authenticateSurfaceTextureLocked(bufferProducer);
647}
648
649bool SurfaceFlinger::authenticateSurfaceTextureLocked(
650 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800651 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700652 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800653}
654
Brian Anderson6b376712017-04-04 10:51:39 -0700655status_t SurfaceFlinger::getSupportedFrameTimestamps(
656 std::vector<FrameEvent>* outSupported) const {
657 *outSupported = {
658 FrameEvent::REQUESTED_PRESENT,
659 FrameEvent::ACQUIRE,
660 FrameEvent::LATCH,
661 FrameEvent::FIRST_REFRESH_START,
662 FrameEvent::LAST_REFRESH_START,
663 FrameEvent::GPU_COMPOSITION_DONE,
664 FrameEvent::DEQUEUE_READY,
665 FrameEvent::RELEASE,
666 };
667 if (!getHwComposer().hasCapability(
668 HWC2::Capability::PresentFenceIsNotReliable)) {
669 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
670 }
671 return NO_ERROR;
672}
673
Dan Stoza7f7da322014-05-02 15:26:25 -0700674status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
675 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700676 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700677 return BAD_VALUE;
678 }
679
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500680 if (!display.get())
681 return NAME_NOT_FOUND;
682
Jesse Hall692c7232012-11-08 15:41:56 -0800683 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700684 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800685 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700686 type = i;
687 break;
688 }
689 }
690
691 if (type < 0) {
692 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700693 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700694
Mathias Agopian8b736f12012-08-13 17:54:26 -0700695 // TODO: Not sure if display density should handled by SF any longer
696 class Density {
697 static int getDensityFromProperty(char const* propName) {
698 char property[PROPERTY_VALUE_MAX];
699 int density = 0;
700 if (property_get(propName, property, NULL) > 0) {
701 density = atoi(property);
702 }
703 return density;
704 }
705 public:
706 static int getEmuDensity() {
707 return getDensityFromProperty("qemu.sf.lcd_density"); }
708 static int getBuildDensity() {
709 return getDensityFromProperty("ro.sf.lcd_density"); }
710 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700711
Dan Stoza7f7da322014-05-02 15:26:25 -0700712 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700713
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700715 DisplayInfo info = DisplayInfo();
716
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717 float xdpi = hwConfig->getDpiX();
718 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700719
720 if (type == DisplayDevice::DISPLAY_PRIMARY) {
721 // The density of the device is provided by a build property
722 float density = Density::getBuildDensity() / 160.0f;
723 if (density == 0) {
724 // the build doesn't provide a density -- this is wrong!
725 // use xdpi instead
726 ALOGE("ro.sf.lcd_density must be defined as a build property");
727 density = xdpi / 160.0f;
728 }
729 if (Density::getEmuDensity()) {
730 // if "qemu.sf.lcd_density" is specified, it overrides everything
731 xdpi = ydpi = density = Density::getEmuDensity();
732 density /= 160.0f;
733 }
734 info.density = density;
735
736 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000737 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
738 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700739 } else {
740 // TODO: where should this value come from?
741 static const int TV_DENSITY = 213;
742 info.density = TV_DENSITY / 160.0f;
743 info.orientation = 0;
744 }
745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 info.w = hwConfig->getWidth();
747 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700748 info.xdpi = xdpi;
749 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900751 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752
Andy McFadden91b2ca82014-06-13 14:04:23 -0700753 // This is how far in advance a buffer must be queued for
754 // presentation at a given time. If you want a buffer to appear
755 // on the screen at time N, you must submit the buffer before
756 // (N - presentationDeadline).
757 //
758 // Normally it's one full refresh period (to give SF a chance to
759 // latch the buffer), but this can be reduced by configuring a
760 // DispSync offset. Any additional delays introduced by the hardware
761 // composer or panel must be accounted for here.
762 //
763 // We add an additional 1ms to allow for processing time and
764 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800766 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700767
768 // All non-virtual displays are currently considered secure.
769 info.secure = true;
770
Michael Wright28f24d02016-07-12 13:30:53 -0700771 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700772 }
773
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 return NO_ERROR;
775}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700776
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800777status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700778 DisplayStatInfo* stats) {
779 if (stats == NULL) {
780 return BAD_VALUE;
781 }
782
783 // FIXME for now we always return stats for the primary display
784 memset(stats, 0, sizeof(*stats));
785 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
786 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
787 return NO_ERROR;
788}
789
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700790int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800791 if (display == NULL) {
792 ALOGE("%s : display is NULL", __func__);
793 return BAD_VALUE;
794 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700795
796 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700797 if (device != NULL) {
798 return device->getActiveConfig();
799 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700800
Dan Stoza24a42e92015-03-09 10:04:11 -0700801 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700803
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700804void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
805 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
806 this);
807 int32_t type = hw->getDisplayType();
808 int currentMode = hw->getActiveConfig();
809
810 if (mode == currentMode) {
811 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
812 return;
813 }
814
815 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
816 ALOGW("Trying to set config for virtual display");
817 return;
818 }
819
820 hw->setActiveConfig(mode);
821 getHwComposer().setActiveConfig(type, mode);
822}
823
824status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
825 class MessageSetActiveConfig: public MessageBase {
826 SurfaceFlinger& mFlinger;
827 sp<IBinder> mDisplay;
828 int mMode;
829 public:
830 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
831 int mode) :
832 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
833 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700834 Vector<DisplayInfo> configs;
835 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700836 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700837 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700838 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700839 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700840 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700841 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
842 if (hw == NULL) {
843 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700844 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700845 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
846 ALOGW("Attempt to set active config = %d for virtual display",
847 mMode);
848 } else {
849 mFlinger.setActiveConfigInternal(hw, mMode);
850 }
851 return true;
852 }
853 };
854 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
855 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700856 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700857}
Michael Wright28f24d02016-07-12 13:30:53 -0700858status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
859 Vector<android_color_mode_t>* outColorModes) {
860 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
861 return BAD_VALUE;
862 }
863
864 if (!display.get()) {
865 return NAME_NOT_FOUND;
866 }
867
868 int32_t type = NAME_NOT_FOUND;
869 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
870 if (display == mBuiltinDisplays[i]) {
871 type = i;
872 break;
873 }
874 }
875
876 if (type < 0) {
877 return type;
878 }
879
880 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
881 outColorModes->clear();
882 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
883
884 return NO_ERROR;
885}
886
887android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700888 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700889 if (device != nullptr) {
890 return device->getActiveColorMode();
891 }
892 return static_cast<android_color_mode_t>(BAD_VALUE);
893}
894
895void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
896 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700897 int32_t type = hw->getDisplayType();
898 android_color_mode_t currentMode = hw->getActiveColorMode();
899
900 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700901 return;
902 }
903
904 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
905 ALOGW("Trying to set config for virtual display");
906 return;
907 }
908
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600909 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
910 hw->getDisplayType());
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 hw->setActiveColorMode(mode);
913 getHwComposer().setActiveColorMode(type, mode);
914}
915
916
917status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
918 android_color_mode_t colorMode) {
919 class MessageSetActiveColorMode: public MessageBase {
920 SurfaceFlinger& mFlinger;
921 sp<IBinder> mDisplay;
922 android_color_mode_t mMode;
923 public:
924 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
925 android_color_mode_t mode) :
926 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
927 virtual bool handler() {
928 Vector<android_color_mode_t> modes;
929 mFlinger.getDisplayColorModes(mDisplay, &modes);
930 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
931 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600932 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
933 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700934 return true;
935 }
936 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
937 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600938 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
939 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700940 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600941 ALOGW("Attempt to set active color mode %s %d for virtual display",
942 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700943 } else {
944 mFlinger.setActiveColorModeInternal(hw, mMode);
945 }
946 return true;
947 }
948 };
949 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
950 postMessageSync(msg);
951 return NO_ERROR;
952}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700953
Svetoslavd85084b2014-03-20 10:28:31 -0700954status_t SurfaceFlinger::clearAnimationFrameStats() {
955 Mutex::Autolock _l(mStateLock);
956 mAnimFrameTracker.clearStats();
957 return NO_ERROR;
958}
959
960status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
961 Mutex::Autolock _l(mStateLock);
962 mAnimFrameTracker.getStats(outStats);
963 return NO_ERROR;
964}
965
Dan Stozac4f471e2016-03-24 09:31:08 -0700966status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
967 HdrCapabilities* outCapabilities) const {
968 Mutex::Autolock _l(mStateLock);
969
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700970 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700971 if (displayDevice == nullptr) {
972 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
973 return BAD_VALUE;
974 }
975
976 std::unique_ptr<HdrCapabilities> capabilities =
977 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
978 if (capabilities) {
979 std::swap(*outCapabilities, *capabilities);
980 } else {
981 return BAD_VALUE;
982 }
983
984 return NO_ERROR;
985}
986
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700987status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
988 if (enable == mInjectVSyncs) {
989 return NO_ERROR;
990 }
991
992 if (enable) {
993 mInjectVSyncs = enable;
994 ALOGV("VSync Injections enabled");
995 if (mVSyncInjector.get() == nullptr) {
996 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700997 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700998 }
999 mEventQueue.setEventThread(mInjectorEventThread);
1000 } else {
1001 mInjectVSyncs = enable;
1002 ALOGV("VSync Injections disabled");
1003 mEventQueue.setEventThread(mSFEventThread);
1004 mVSyncInjector.clear();
1005 }
1006 return NO_ERROR;
1007}
1008
1009status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1010 if (!mInjectVSyncs) {
1011 ALOGE("VSync Injections not enabled");
1012 return BAD_VALUE;
1013 }
1014 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1015 ALOGV("Injecting VSync inside SurfaceFlinger");
1016 mVSyncInjector->onInjectSyncEvent(when);
1017 }
1018 return NO_ERROR;
1019}
1020
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001021// ----------------------------------------------------------------------------
1022
1023sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001024 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001025}
1026
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001027// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001028
1029void SurfaceFlinger::waitForEvent() {
1030 mEventQueue.waitMessage();
1031}
1032
1033void SurfaceFlinger::signalTransaction() {
1034 mEventQueue.invalidate();
1035}
1036
1037void SurfaceFlinger::signalLayerUpdate() {
1038 mEventQueue.invalidate();
1039}
1040
1041void SurfaceFlinger::signalRefresh() {
1042 mEventQueue.refresh();
1043}
1044
1045status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001046 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001047 return mEventQueue.postMessage(msg, reltime);
1048}
1049
1050status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001051 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001052 status_t res = mEventQueue.postMessage(msg, reltime);
1053 if (res == NO_ERROR) {
1054 msg->wait();
1055 }
1056 return res;
1057}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001058
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001059void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001060 do {
1061 waitForEvent();
1062 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001063}
1064
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001065void SurfaceFlinger::enableHardwareVsync() {
1066 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001067 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001068 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001069 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1070 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001072 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073}
1074
Jesse Hall948fe0c2013-10-14 12:56:09 -07001075void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 Mutex::Autolock _l(mHWVsyncLock);
1077
Jesse Hall948fe0c2013-10-14 12:56:09 -07001078 if (makeAvailable) {
1079 mHWVsyncAvailable = true;
1080 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001081 // Hardware vsync is not currently available, so abort the resync
1082 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001083 return;
1084 }
1085
Dan Stoza9e56aa02015-11-02 13:00:03 -08001086 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1087 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001088
1089 mPrimaryDispSync.reset();
1090 mPrimaryDispSync.setPeriod(period);
1091
1092 if (!mPrimaryHWVsyncEnabled) {
1093 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001094 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1095 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001096 mPrimaryHWVsyncEnabled = true;
1097 }
1098}
1099
Jesse Hall948fe0c2013-10-14 12:56:09 -07001100void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001101 Mutex::Autolock _l(mHWVsyncLock);
1102 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001103 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1104 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001105 mPrimaryDispSync.endResync();
1106 mPrimaryHWVsyncEnabled = false;
1107 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001108 if (makeUnavailable) {
1109 mHWVsyncAvailable = false;
1110 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111}
1112
Tim Murray4a4e4a22016-04-19 16:29:23 +00001113void SurfaceFlinger::resyncWithRateLimit() {
1114 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1115 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001116 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001117 }
1118}
1119
Steven Thomas3cfac282017-02-06 12:29:30 -08001120void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1121 nsecs_t timestamp) {
1122 Mutex::Autolock lock(mStateLock);
1123 // Ignore any vsyncs from the non-active hardware composer.
1124 if (composer != mHwc) {
1125 return;
1126 }
1127
Jamie Gennisd1700752013-10-14 12:22:52 -07001128 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001129
Jamie Gennisd1700752013-10-14 12:22:52 -07001130 { // Scope for the lock
1131 Mutex::Autolock _l(mHWVsyncLock);
1132 if (type == 0 && mPrimaryHWVsyncEnabled) {
1133 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001134 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001135 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001136
1137 if (needsHwVsync) {
1138 enableHardwareVsync();
1139 } else {
1140 disableHardwareVsync(false);
1141 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001142}
1143
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001144void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001145 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001146 *compositorTiming = mCompositorTiming;
1147}
1148
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001149void SurfaceFlinger::createDefaultDisplayDevice() {
1150 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1151 wp<IBinder> token = mBuiltinDisplays[type];
1152
1153 // All non-virtual displays are currently considered secure.
1154 const bool isSecure = true;
1155
1156 sp<IGraphicBufferProducer> producer;
1157 sp<IGraphicBufferConsumer> consumer;
1158 BufferQueue::createBufferQueue(&producer, &consumer);
1159
1160 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1161
1162 bool hasWideColorModes = false;
1163 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1164 for (android_color_mode_t colorMode : modes) {
1165 switch (colorMode) {
1166 case HAL_COLOR_MODE_DISPLAY_P3:
1167 case HAL_COLOR_MODE_ADOBE_RGB:
1168 case HAL_COLOR_MODE_DCI_P3:
1169 hasWideColorModes = true;
1170 break;
1171 default:
1172 break;
1173 }
1174 }
1175 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1176 token, fbs, producer, mRenderEngine->getEGLConfig(),
1177 hasWideColorModes && hasWideColorDisplay);
1178 mDisplays.add(token, hw);
1179 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1180 if (hasWideColorModes && hasWideColorDisplay) {
1181 defaultColorMode = HAL_COLOR_MODE_SRGB;
1182 }
1183 setActiveColorModeInternal(hw, defaultColorMode);
1184}
1185
1186void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001188
1189 if (composer->isUsingVrComposer()) {
1190 // We handle initializing the primary display device for the VR
1191 // window manager hwc explicitly at the time of transition.
1192 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1193 ALOGE("External displays are not supported by the vr hardware composer.");
1194 }
1195 return;
1196 }
1197
Dan Stoza9e56aa02015-11-02 13:00:03 -08001198 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1199 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001200 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1201 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001202 } else {
1203 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001204 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001205 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001206 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001207 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001208 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1209 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001210 }
1211 setTransactionFlags(eDisplayTransactionNeeded);
1212
Andy McFadden9e9689c2012-10-10 18:17:51 -07001213 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001214 }
Mathias Agopian86303202012-07-24 22:46:10 -07001215}
1216
Steven Thomas3cfac282017-02-06 12:29:30 -08001217void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1218 Mutex::Autolock lock(mStateLock);
1219 if (composer == mHwc) {
1220 repaintEverything();
1221 } else {
1222 // This isn't from our current hardware composer. If it's a callback
1223 // from the real composer, forward the refresh request to vr
1224 // flinger. Otherwise ignore it.
1225 if (!composer->isUsingVrComposer()) {
1226 mVrFlinger->OnHardwareComposerRefresh();
1227 }
1228 }
1229}
1230
Dan Stoza9e56aa02015-11-02 13:00:03 -08001231void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001232 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 getHwComposer().setVsyncEnabled(disp,
1234 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001235}
1236
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001237void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1238 for (size_t i = 0; i < layers.size(); ++i) {
1239 layers[i]->clearHwcLayers();
1240 }
1241}
1242
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001243// Note: it is assumed the caller holds |mStateLock| when this is called
1244void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001245 disableHardwareVsync(true);
1246 clearHwcLayers(mDrawingState.layersSortedByZ);
1247 clearHwcLayers(mCurrentState.layersSortedByZ);
1248 // Clear the drawing state so that the logic inside of
1249 // handleTransactionLocked will fire. It will determine the delta between
1250 // mCurrentState and mDrawingState and re-apply all changes when we make the
1251 // transition.
1252 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001253 // Release virtual display hwcId during vr mode transition.
1254 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1255 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1256 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1257 displayDevice->disconnect(getHwComposer());
1258 }
1259 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001260 mDisplays.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -08001261 initializeDisplays();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001262}
1263
Steven Thomas050b2c82017-03-06 11:45:16 -08001264void SurfaceFlinger::updateVrFlinger() {
1265 if (!mVrFlinger)
1266 return;
1267 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1268 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001269 return;
1270 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001271
Steven Thomas050b2c82017-03-06 11:45:16 -08001272 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001273 // Construct new HWComposer without holding any locks.
1274 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001275
1276 // Set up the event handlers. This step is neccessary to initialize the internal state of
1277 // the hardware composer object properly. Our callbacks are designed such that if they are
1278 // triggered between now and the point where the display is properly re-initialized, they
1279 // will not have any effect, so this is safe to do here, before the lock is aquired.
1280 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001281 ALOGV("Vr HWC created");
1282 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001283
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001285
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286 if (vrFlingerRequestsDisplay) {
1287 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001288
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001289 mHwc = mVrHwc;
1290 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001291
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292 } else {
1293 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001295 resetHwcLocked();
1296
1297 mHwc = mRealHwc;
1298 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001299 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300
1301 mVisibleRegionsDirty = true;
1302 invalidateHwcGeometry();
1303
1304 // Explicitly re-initialize the primary display. This is because some other
1305 // parts of this class rely on the primary display always being available.
1306 createDefaultDisplayDevice();
1307
1308 android_atomic_or(1, &mRepaintEverything);
1309 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001310}
1311
Mathias Agopian4fec8732012-06-29 14:12:52 -07001312void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001313 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001314 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001315 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001316 bool frameMissed = !mHadClientComposition &&
1317 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001318 (mPreviousPresentFence->getSignalTime() ==
1319 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001320 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001321 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001322 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001323 signalLayerUpdate();
1324 break;
1325 }
1326
Steven Thomas050b2c82017-03-06 11:45:16 -08001327 // Now that we're going to make it to the handleMessageTransaction()
1328 // call below it's safe to call updateVrFlinger(), which will
1329 // potentially trigger a display handoff.
1330 updateVrFlinger();
1331
Dan Stoza6b9454d2014-11-07 16:00:59 -08001332 bool refreshNeeded = handleMessageTransaction();
1333 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001334 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001335 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001336 // Signal a refresh if a transaction modified the window state,
1337 // a new buffer was latched, or if HWC has requested a full
1338 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001339 signalRefresh();
1340 }
1341 break;
1342 }
1343 case MessageQueue::REFRESH: {
1344 handleMessageRefresh();
1345 break;
1346 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347 }
1348}
1349
Dan Stoza6b9454d2014-11-07 16:00:59 -08001350bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001351 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001352 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001353 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001354 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001355 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001356 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001357}
1358
Dan Stoza6b9454d2014-11-07 16:00:59 -08001359bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001360 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001361 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001362}
1363
1364void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001365 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001366
Pablo Ceballos40845df2016-01-25 17:41:15 -08001367 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001368
Brian Andersond6927fb2016-07-23 23:37:30 -07001369 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001370 rebuildLayerStacks();
1371 setUpHWComposer();
1372 doDebugFlashRegions();
1373 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001374 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001375
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001376 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001377
1378 mHadClientComposition = false;
1379 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1380 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1381 mHadClientComposition = mHadClientComposition ||
1382 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1383 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001384
Dan Stoza9e56aa02015-11-02 13:00:03 -08001385 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001387
Mathias Agopiancd60f992012-08-16 16:28:27 -07001388void SurfaceFlinger::doDebugFlashRegions()
1389{
1390 // is debugging enabled
1391 if (CC_LIKELY(!mDebugRegion))
1392 return;
1393
1394 const bool repaintEverything = mRepaintEverything;
1395 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1396 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001397 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001398 // transform the dirty region into this screen's coordinate space
1399 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1400 if (!dirtyRegion.isEmpty()) {
1401 // redraw the whole screen
1402 doComposeSurfaces(hw, Region(hw->bounds()));
1403
1404 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001405 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001406 RenderEngine& engine(getRenderEngine());
1407 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1408
Mathias Agopianda27af92012-09-13 18:17:13 -07001409 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001410 }
1411 }
1412 }
1413
1414 postFramebuffer();
1415
1416 if (mDebugRegion > 1) {
1417 usleep(mDebugRegion * 1000);
1418 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001419
Dan Stoza9e56aa02015-11-02 13:00:03 -08001420 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001421 auto& displayDevice = mDisplays[displayId];
1422 if (!displayDevice->isDisplayOn()) {
1423 continue;
1424 }
1425
1426 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001427 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1428 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001429 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001430}
1431
Brian Andersond6927fb2016-07-23 23:37:30 -07001432void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001434 ATRACE_CALL();
1435 ALOGV("preComposition");
1436
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001438 mDrawingState.traverseInZOrder([&](Layer* layer) {
1439 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 needExtraInvalidate = true;
1441 }
Robert Carr2047fae2016-11-28 14:09:09 -08001442 });
1443
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444 if (needExtraInvalidate) {
1445 signalLayerUpdate();
1446 }
1447}
1448
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001449void SurfaceFlinger::updateCompositorTiming(
1450 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1451 std::shared_ptr<FenceTime>& presentFenceTime) {
1452 // Update queue of past composite+present times and determine the
1453 // most recently known composite to present latency.
1454 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1455 nsecs_t compositeToPresentLatency = -1;
1456 while (!mCompositePresentTimes.empty()) {
1457 CompositePresentTime& cpt = mCompositePresentTimes.front();
1458 // Cached values should have been updated before calling this method,
1459 // which helps avoid duplicate syscalls.
1460 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1461 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1462 break;
1463 }
1464 compositeToPresentLatency = displayTime - cpt.composite;
1465 mCompositePresentTimes.pop();
1466 }
1467
1468 // Don't let mCompositePresentTimes grow unbounded, just in case.
1469 while (mCompositePresentTimes.size() > 16) {
1470 mCompositePresentTimes.pop();
1471 }
1472
Brian Andersond0010582017-03-07 13:20:31 -08001473 setCompositorTimingSnapped(
1474 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1475}
1476
1477void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1478 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 // Integer division and modulo round toward 0 not -inf, so we need to
1480 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001481 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1483 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1484
Brian Andersond0010582017-03-07 13:20:31 -08001485 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1486 if (idealLatency <= 0) {
1487 idealLatency = vsyncInterval;
1488 }
1489
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001490 // Snap the latency to a value that removes scheduling jitter from the
1491 // composition and present times, which often have >1ms of jitter.
1492 // Reducing jitter is important if an app attempts to extrapolate
1493 // something (such as user input) to an accurate diasplay time.
1494 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1495 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001496 nsecs_t bias = vsyncInterval / 2;
1497 int64_t extraVsyncs =
1498 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1499 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1500 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001501
Brian Andersond0010582017-03-07 13:20:31 -08001502 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001503 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1504 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001505 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506}
1507
1508void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001510 ATRACE_CALL();
1511 ALOGV("postComposition");
1512
Brian Anderson3546a3f2016-07-14 11:51:14 -07001513 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001514 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001515 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001516 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001517 }
1518
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001519 // |mStateLock| not needed as we are on the main thread
1520 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001521
1522 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1523 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1524 glCompositionDoneFenceTime =
1525 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1526 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1527 } else {
1528 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1529 }
1530 mGlCompositionDoneTimeline.updateSignalTimes();
1531
Brian Anderson4e606e32017-03-16 15:34:57 -07001532 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1533 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1534 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001535 mDisplayTimeline.updateSignalTimes();
1536
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1538 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1539
1540 // We use the refreshStartTime which might be sampled a little later than
1541 // when we started doing work for this frame, but that should be okay
1542 // since updateCompositorTiming has snapping logic.
1543 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001544 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001545 CompositorTiming compositorTiming;
1546 {
1547 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1548 compositorTiming = mCompositorTiming;
1549 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001550
Robert Carr2047fae2016-11-28 14:09:09 -08001551 mDrawingState.traverseInZOrder([&](Layer* layer) {
1552 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001553 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001554 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001555 recordBufferingStats(layer->getName().string(),
1556 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001557 }
Robert Carr2047fae2016-11-28 14:09:09 -08001558 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001559
Brian Anderson4e606e32017-03-16 15:34:57 -07001560 if (presentFence->isValid()) {
1561 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001562 enableHardwareVsync();
1563 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001564 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001565 }
1566 }
1567
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001568 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001569 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001570 enableHardwareVsync();
1571 }
1572 }
1573
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001574 if (mAnimCompositionPending) {
1575 mAnimCompositionPending = false;
1576
Brian Anderson4e606e32017-03-16 15:34:57 -07001577 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001578 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001579 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001580 } else {
1581 // The HWC doesn't support present fences, so use the refresh
1582 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001583 nsecs_t presentTime =
1584 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001585 mAnimFrameTracker.setActualPresentTime(presentTime);
1586 }
1587 mAnimFrameTracker.advanceFrame();
1588 }
Dan Stozab90cf072015-03-05 11:05:59 -08001589
1590 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1591 return;
1592 }
1593
1594 nsecs_t currentTime = systemTime();
1595 if (mHasPoweredOff) {
1596 mHasPoweredOff = false;
1597 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001598 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001599 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001600 if (numPeriods < NUM_BUCKETS - 1) {
1601 mFrameBuckets[numPeriods] += elapsedTime;
1602 } else {
1603 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1604 }
1605 mTotalTime += elapsedTime;
1606 }
1607 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608}
1609
1610void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001611 ATRACE_CALL();
1612 ALOGV("rebuildLayerStacks");
1613
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001615 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1616 ATRACE_CALL();
1617 mVisibleRegionsDirty = false;
1618 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001619
Jeff Sharkey76488112017-02-27 14:15:18 -07001620 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1621 Region opaqueRegion;
1622 Region dirtyRegion;
1623 Vector<sp<Layer>> layersSortedByZ;
1624 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1625 const Transform& tr(displayDevice->getTransform());
1626 const Rect bounds(displayDevice->getBounds());
1627 if (displayDevice->isDisplayOn()) {
1628 computeVisibleRegions(
1629 displayDevice->getLayerStack(), dirtyRegion,
1630 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001631
Jeff Sharkey76488112017-02-27 14:15:18 -07001632 mDrawingState.traverseInZOrder([&](Layer* layer) {
1633 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1634 Region drawRegion(tr.transform(
1635 layer->visibleNonTransparentRegion));
1636 drawRegion.andSelf(bounds);
1637 if (!drawRegion.isEmpty()) {
1638 layersSortedByZ.add(layer);
1639 } else {
1640 // Clear out the HWC layer if this layer was
1641 // previously visible, but no longer is
1642 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1643 nullptr);
1644 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001645 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001646 // WM changes displayDevice->layerStack upon sleep/awake.
1647 // Here we make sure we delete the HWC layers even if
1648 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001649 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1650 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001651 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001652 });
1653 }
1654 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1655 displayDevice->undefinedRegion.set(bounds);
1656 displayDevice->undefinedRegion.subtractSelf(
1657 tr.transform(opaqueRegion));
1658 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001659 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001660 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001661}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001662
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001663// pickColorMode translates a given dataspace into the best available color mode.
1664// Currently only support sRGB and Display-P3.
1665android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1666 switch (dataSpace) {
1667 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1668 // system expects.
1669 case HAL_DATASPACE_UNKNOWN:
1670 case HAL_DATASPACE_SRGB:
1671 case HAL_DATASPACE_V0_SRGB:
1672 return HAL_COLOR_MODE_SRGB;
1673 break;
1674
1675 case HAL_DATASPACE_DISPLAY_P3:
1676 return HAL_COLOR_MODE_DISPLAY_P3;
1677 break;
1678
1679 default:
1680 // TODO (courtneygo): Do we want to assert an error here?
1681 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1682 dataSpace);
1683 return HAL_COLOR_MODE_SRGB;
1684 break;
1685 }
1686}
1687
1688android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1689 // Only support sRGB and Display-P3 right now.
1690 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1691 return HAL_DATASPACE_DISPLAY_P3;
1692 }
1693 return HAL_DATASPACE_V0_SRGB;
1694}
1695
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 ATRACE_CALL();
1698 ALOGV("setUpHWComposer");
1699
Jesse Hall028dc8f2013-08-20 16:35:32 -07001700 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001701 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1702 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1703 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1704
1705 // If nothing has changed (!dirty), don't recompose.
1706 // If something changed, but we don't currently have any visible layers,
1707 // and didn't when we last did a composition, then skip it this time.
1708 // The second rule does two things:
1709 // - When all layers are removed from a display, we'll emit one black
1710 // frame, then nothing more until we get new layers.
1711 // - When a display is created with a private layer stack, we won't
1712 // emit any black frames until a layer is added to the layer stack.
1713 bool mustRecompose = dirty && !(empty && wasEmpty);
1714
1715 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1716 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1717 mustRecompose ? "doing" : "skipping",
1718 dirty ? "+" : "-",
1719 empty ? "+" : "-",
1720 wasEmpty ? "+" : "-");
1721
Dan Stoza71433162014-02-04 16:22:36 -08001722 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001723
1724 if (mustRecompose) {
1725 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1726 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001727 }
1728
Dan Stoza9e56aa02015-11-02 13:00:03 -08001729 // build the h/w work list
1730 if (CC_UNLIKELY(mGeometryInvalid)) {
1731 mGeometryInvalid = false;
1732 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1733 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1734 const auto hwcId = displayDevice->getHwcDisplayId();
1735 if (hwcId >= 0) {
1736 const Vector<sp<Layer>>& currentLayers(
1737 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001738 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001739 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001740 if (!layer->hasHwcLayer(hwcId)) {
1741 auto hwcLayer = mHwc->createLayer(hwcId);
1742 if (hwcLayer) {
1743 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1744 } else {
1745 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001746 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001747 }
1748 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001749
Robert Carrae060832016-11-28 10:51:00 -08001750 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001751 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001753 }
1754 }
1755 }
1756 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 }
Riley Andrews03414a12014-07-01 14:22:59 -07001758
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001759
1760 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1761
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762 // Set the per-frame data
1763 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1764 auto& displayDevice = mDisplays[displayId];
1765 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001766
Dan Stoza9e56aa02015-11-02 13:00:03 -08001767 if (hwcId < 0) {
1768 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001769 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001770 if (colorMatrix != mPreviousColorMatrix) {
1771 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1772 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1773 "display %zd: %d", displayId, result);
1774 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001775 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1776 layer->setPerFrameData(displayDevice);
1777 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001778
1779 if (hasWideColorDisplay) {
1780 android_color_mode newColorMode;
1781 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1782
1783 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1784 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1785 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1786 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1787 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1788 }
1789 newColorMode = pickColorMode(newDataSpace);
1790
1791 setActiveColorModeInternal(displayDevice, newColorMode);
1792 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001793 }
1794
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001795 mPreviousColorMatrix = colorMatrix;
1796
Dan Stoza9e56aa02015-11-02 13:00:03 -08001797 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001798 auto& displayDevice = mDisplays[displayId];
1799 if (!displayDevice->isDisplayOn()) {
1800 continue;
1801 }
1802
1803 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001804 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1805 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001806 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001808
Mathias Agopiancd60f992012-08-16 16:28:27 -07001809void SurfaceFlinger::doComposition() {
1810 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 ALOGV("doComposition");
1812
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001813 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001814 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001815 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001816 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001817 // transform the dirty region into this screen's coordinate space
1818 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001819
1820 // repaint the framebuffer (if needed)
1821 doDisplayComposition(hw, dirtyRegion);
1822
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823 hw->dirtyRegion.clear();
1824 hw->flip(hw->swapRegion);
1825 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001826 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001827 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001828 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001829}
1830
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831void SurfaceFlinger::postFramebuffer()
1832{
Mathias Agopian841cde52012-03-01 15:44:37 -08001833 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001835
Mathias Agopiana44b0412011-10-16 18:46:35 -07001836 const nsecs_t now = systemTime();
1837 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001838
Dan Stoza9e56aa02015-11-02 13:00:03 -08001839 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1840 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001841 if (!displayDevice->isDisplayOn()) {
1842 continue;
1843 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 const auto hwcId = displayDevice->getHwcDisplayId();
1845 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001846 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001847 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001848 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001849 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001850 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1851 sp<Fence> releaseFence = Fence::NO_FENCE;
1852 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1853 releaseFence = displayDevice->getClientTargetAcquireFence();
1854 } else {
1855 auto hwcLayer = layer->getHwcLayer(hwcId);
1856 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001857 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 layer->onLayerDisplayed(releaseFence);
1859 }
1860 if (hwcId >= 0) {
1861 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001862 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001863 }
1864
Mathias Agopiana44b0412011-10-16 18:46:35 -07001865 mLastSwapBufferTime = systemTime() - now;
1866 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001867
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001868 // |mStateLock| not needed as we are on the main thread
1869 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001870 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1871 logFrameStats();
1872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001873}
1874
Mathias Agopian87baae12012-07-31 12:38:26 -07001875void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001876{
Mathias Agopian841cde52012-03-01 15:44:37 -08001877 ATRACE_CALL();
1878
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001879 // here we keep a copy of the drawing state (that is the state that's
1880 // going to be overwritten by handleTransactionLocked()) outside of
1881 // mStateLock so that the side-effects of the State assignment
1882 // don't happen with mStateLock held (which can cause deadlocks).
1883 State drawingState(mDrawingState);
1884
Mathias Agopianca4d3602011-05-19 15:38:14 -07001885 Mutex::Autolock _l(mStateLock);
1886 const nsecs_t now = systemTime();
1887 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001888
Mathias Agopianca4d3602011-05-19 15:38:14 -07001889 // Here we're guaranteed that some transaction flags are set
1890 // so we can call handleTransactionLocked() unconditionally.
1891 // We call getTransactionFlags(), which will also clear the flags,
1892 // with mStateLock held to guarantee that mCurrentState won't change
1893 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001894
Mathias Agopiane57f2922012-08-09 16:29:12 -07001895 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001896 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001897
Mathias Agopianca4d3602011-05-19 15:38:14 -07001898 mLastTransactionTime = systemTime() - now;
1899 mDebugInTransaction = 0;
1900 invalidateHwcGeometry();
1901 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001902}
1903
Mathias Agopian87baae12012-07-31 12:38:26 -07001904void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001905{
Dan Stoza7dde5992015-05-22 09:51:44 -07001906 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001907 mCurrentState.traverseInZOrder([](Layer* layer) {
1908 layer->notifyAvailableFrames();
1909 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001910
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911 /*
1912 * Traversal of the children
1913 * (perform the transaction for each of them if needed)
1914 */
1915
Mathias Agopian3559b072012-08-15 13:46:03 -07001916 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001917 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001919 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001920
1921 const uint32_t flags = layer->doTransaction(0);
1922 if (flags & Layer::eVisibleRegion)
1923 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001924 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925 }
1926
1927 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001928 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929 */
1930
Mathias Agopiane57f2922012-08-09 16:29:12 -07001931 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001932 // here we take advantage of Vector's copy-on-write semantics to
1933 // improve performance by skipping the transaction entirely when
1934 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001935 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1936 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001937 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001939 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001940 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001941
1942 // find the displays that were removed
1943 // (ie: in drawing state but not in current state)
1944 // also handle displays that changed
1945 // (ie: displays that are in both lists)
1946 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001947 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1948 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001949 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001950 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001951 // Call makeCurrent() on the primary display so we can
1952 // be sure that nothing associated with this display
1953 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001954 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001955 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001956 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07001957 if (hw != NULL)
1958 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001959 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001960 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001961 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001962 } else {
1963 ALOGW("trying to remove the main display");
1964 }
1965 } else {
1966 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001967 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001968 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001969 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1970 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001971 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001972 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001973 // recreating the DisplayDevice, so we just remove it
1974 // from the drawing state, so that it get re-added
1975 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001976 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07001977 if (hw != NULL)
1978 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001979 mDisplays.removeItem(display);
1980 mDrawingState.displays.removeItemsAt(i);
1981 dc--; i--;
1982 // at this point we must loop to the next item
1983 continue;
1984 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001985
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001986 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001987 if (disp != NULL) {
1988 if (state.layerStack != draw[i].layerStack) {
1989 disp->setLayerStack(state.layerStack);
1990 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001991 if ((state.orientation != draw[i].orientation)
1992 || (state.viewport != draw[i].viewport)
1993 || (state.frame != draw[i].frame))
1994 {
1995 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001996 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001997 }
Michael Lentine47e45402014-07-18 15:34:25 -07001998 if (state.width != draw[i].width || state.height != draw[i].height) {
1999 disp->setDisplaySize(state.width, state.height);
2000 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002001 }
2002 }
2003 }
2004
2005 // find displays that were added
2006 // (ie: in current state but not in drawing state)
2007 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002008 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002009 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002010
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002011 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002012 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002013 sp<IGraphicBufferProducer> bqProducer;
2014 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002015 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002016
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002018 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002019 // Virtual displays without a surface are dormant:
2020 // they have external state (layer stack, projection,
2021 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002022 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002023
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002024 // Allow VR composer to use virtual displays.
2025 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002026 int width = 0;
2027 int status = state.surface->query(
2028 NATIVE_WINDOW_WIDTH, &width);
2029 ALOGE_IF(status != NO_ERROR,
2030 "Unable to query width (%d)", status);
2031 int height = 0;
2032 status = state.surface->query(
2033 NATIVE_WINDOW_HEIGHT, &height);
2034 ALOGE_IF(status != NO_ERROR,
2035 "Unable to query height (%d)", status);
2036 int intFormat = 0;
2037 status = state.surface->query(
2038 NATIVE_WINDOW_FORMAT, &intFormat);
2039 ALOGE_IF(status != NO_ERROR,
2040 "Unable to query format (%d)", status);
2041 auto format = static_cast<android_pixel_format_t>(
2042 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002043
Dan Stoza8cf150a2016-08-02 10:27:31 -07002044 mHwc->allocateVirtualDisplay(width, height, &format,
2045 &hwcId);
2046 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047
Dan Stoza5cf424b2016-05-20 14:02:39 -07002048 // TODO: Plumb requested format back up to consumer
2049
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 sp<VirtualDisplaySurface> vds =
2051 new VirtualDisplaySurface(*mHwc,
2052 hwcId, state.surface, bqProducer,
2053 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002054
2055 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002056 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002057 }
2058 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002059 ALOGE_IF(state.surface!=NULL,
2060 "adding a supported display, but rendering "
2061 "surface is provided (%p), ignoring it",
2062 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002063
2064 hwcId = state.type;
2065 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2066 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002067 }
2068
2069 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002070 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002071 sp<DisplayDevice> hw =
2072 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2073 dispSurface, producer,
2074 mRenderEngine->getEGLConfig(),
2075 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002076 hw->setLayerStack(state.layerStack);
2077 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002078 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002079 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002080 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002082 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002083 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002084 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002085 }
2086 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002087 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002088 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002089
Mathias Agopian84300952012-11-21 16:02:13 -08002090 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2091 // The transform hint might have changed for some layers
2092 // (either because a display has changed, or because a layer
2093 // as changed).
2094 //
2095 // Walk through all the layers in currentLayers,
2096 // and update their transform hint.
2097 //
2098 // If a layer is visible only on a single display, then that
2099 // display is used to calculate the hint, otherwise we use the
2100 // default display.
2101 //
2102 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2103 // the hint is set before we acquire a buffer from the surface texture.
2104 //
2105 // NOTE: layer transactions have taken place already, so we use their
2106 // drawing state. However, SurfaceFlinger's own transaction has not
2107 // happened yet, so we must use the current state layer list
2108 // (soon to become the drawing state list).
2109 //
2110 sp<const DisplayDevice> disp;
2111 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002112 bool first = true;
2113 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002114 // NOTE: we rely on the fact that layers are sorted by
2115 // layerStack first (so we don't have to traverse the list
2116 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002117 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002118 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002119 currentlayerStack = layerStack;
2120 // figure out if this layerstack is mirrored
2121 // (more than one display) if so, pick the default display,
2122 // if not, pick the only display it's on.
2123 disp.clear();
2124 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2125 sp<const DisplayDevice> hw(mDisplays[dpy]);
2126 if (hw->getLayerStack() == currentlayerStack) {
2127 if (disp == NULL) {
2128 disp = hw;
2129 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002130 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002131 break;
2132 }
2133 }
2134 }
2135 }
Chet Haase91d25932013-04-11 15:24:55 -07002136 if (disp == NULL) {
2137 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2138 // redraw after transform hint changes. See bug 8508397.
2139
2140 // could be null when this layer is using a layerStack
2141 // that is not visible on any display. Also can occur at
2142 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002143 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002144 }
Chet Haase91d25932013-04-11 15:24:55 -07002145 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002146
2147 first = false;
2148 });
Mathias Agopian84300952012-11-21 16:02:13 -08002149 }
2150
2151
Mathias Agopian3559b072012-08-15 13:46:03 -07002152 /*
2153 * Perform our own transaction if needed
2154 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002155
2156 if (mLayersAdded) {
2157 mLayersAdded = false;
2158 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002159 mVisibleRegionsDirty = true;
2160 }
2161
2162 // some layers might have been removed, so
2163 // we need to update the regions they're exposing.
2164 if (mLayersRemoved) {
2165 mLayersRemoved = false;
2166 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002167 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002168 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002169 // this layer is not visible anymore
2170 // TODO: we could traverse the tree from front to back and
2171 // compute the actual visible region
2172 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002173 Region visibleReg;
2174 visibleReg.set(layer->computeScreenBounds());
2175 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002176 }
Robert Carr2047fae2016-11-28 14:09:09 -08002177 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178 }
2179
2180 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002181
2182 updateCursorAsync();
2183}
2184
2185void SurfaceFlinger::updateCursorAsync()
2186{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002187 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2188 auto& displayDevice = mDisplays[displayId];
2189 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002190 continue;
2191 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002192
2193 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2194 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002195 }
2196 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002197}
2198
2199void SurfaceFlinger::commitTransaction()
2200{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002201 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002202 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002203 for (const auto& l : mLayersPendingRemoval) {
2204 recordBufferingStats(l->getName().string(),
2205 l->getOccupancyHistory(true));
2206 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002207 }
2208 mLayersPendingRemoval.clear();
2209 }
2210
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002211 // If this transaction is part of a window animation then the next frame
2212 // we composite should be considered an animation as well.
2213 mAnimCompositionPending = mAnimTransactionPending;
2214
Mathias Agopian4fec8732012-06-29 14:12:52 -07002215 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002216 mDrawingState.traverseInZOrder([](Layer* layer) {
2217 layer->commitChildList();
2218 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002219 mTransactionPending = false;
2220 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002221 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002222}
2223
Robert Carr2047fae2016-11-28 14:09:09 -08002224void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002225 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226{
Mathias Agopian841cde52012-03-01 15:44:37 -08002227 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 Region aboveOpaqueLayers;
2231 Region aboveCoveredLayers;
2232 Region dirty;
2233
Mathias Agopian87baae12012-07-31 12:38:26 -07002234 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235
Robert Carr2047fae2016-11-28 14:09:09 -08002236 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002238 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002239
Jesse Hall01e29052013-02-19 16:13:35 -08002240 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002241 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002242 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002243
Mathias Agopianab028732010-03-16 16:41:46 -07002244 /*
2245 * opaqueRegion: area of a surface that is fully opaque.
2246 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002248
2249 /*
2250 * visibleRegion: area of a surface that is visible on screen
2251 * and not fully transparent. This is essentially the layer's
2252 * footprint minus the opaque regions above it.
2253 * Areas covered by a translucent surface are considered visible.
2254 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002256
2257 /*
2258 * coveredRegion: area of a surface that is covered by all
2259 * visible regions above it (which includes the translucent areas).
2260 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002262
Jesse Halla8026d22012-09-25 13:25:04 -07002263 /*
2264 * transparentRegion: area of a surface that is hinted to be completely
2265 * transparent. This is only used to tell when the layer has no visible
2266 * non-transparent regions and can be removed from the layer list. It
2267 * does not affect the visibleRegion of this layer or any layers
2268 * beneath it. The hint may not be correct if apps don't respect the
2269 * SurfaceView restrictions (which, sadly, some don't).
2270 */
2271 Region transparentRegion;
2272
Mathias Agopianab028732010-03-16 16:41:46 -07002273
2274 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002275 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002276 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002278 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002279 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002280 if (!visibleRegion.isEmpty()) {
2281 // Remove the transparent area from the visible region
2282 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002283 if (tr.preserveRects()) {
2284 // transform the transparent region
2285 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002287 // transformation too complex, can't do the
2288 // transparent region optimization.
2289 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 }
Mathias Agopianab028732010-03-16 16:41:46 -07002291 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292
Mathias Agopianab028732010-03-16 16:41:46 -07002293 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002295 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002296 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2297 // the opaque region is the layer's footprint
2298 opaqueRegion = visibleRegion;
2299 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 }
2301 }
2302
Mathias Agopianab028732010-03-16 16:41:46 -07002303 // Clip the covered region to the visible region
2304 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2305
2306 // Update aboveCoveredLayers for next (lower) layer
2307 aboveCoveredLayers.orSelf(visibleRegion);
2308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309 // subtract the opaque region covered by the layers above us
2310 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311
2312 // compute this layer's dirty region
2313 if (layer->contentDirty) {
2314 // we need to invalidate the whole region
2315 dirty = visibleRegion;
2316 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002317 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318 layer->contentDirty = false;
2319 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002320 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002321 * the exposed region consists of two components:
2322 * 1) what's VISIBLE now and was COVERED before
2323 * 2) what's EXPOSED now less what was EXPOSED before
2324 *
2325 * note that (1) is conservative, we start with the whole
2326 * visible region but only keep what used to be covered by
2327 * something -- which mean it may have been exposed.
2328 *
2329 * (2) handles areas that were not covered by anything but got
2330 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002331 */
Mathias Agopianab028732010-03-16 16:41:46 -07002332 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002333 const Region oldVisibleRegion = layer->visibleRegion;
2334 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002335 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2336 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 }
2338 dirty.subtractSelf(aboveOpaqueLayers);
2339
2340 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002341 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342
Mathias Agopianab028732010-03-16 16:41:46 -07002343 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002345
Jesse Halla8026d22012-09-25 13:25:04 -07002346 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 layer->setVisibleRegion(visibleRegion);
2348 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002349 layer->setVisibleNonTransparentRegion(
2350 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002351 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352
Mathias Agopian87baae12012-07-31 12:38:26 -07002353 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2357 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002358 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002359 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2360 if (hw->getLayerStack() == layerStack) {
2361 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002362 }
2363 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002364}
2365
Dan Stoza6b9454d2014-11-07 16:00:59 -08002366bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002368 ALOGV("handlePageFlip");
2369
Brian Andersond6927fb2016-07-23 23:37:30 -07002370 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002371
Mathias Agopian4fec8732012-06-29 14:12:52 -07002372 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002373 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002374 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002375
2376 // Store the set of layers that need updates. This set must not change as
2377 // buffers are being latched, as this could result in a deadlock.
2378 // Example: Two producers share the same command stream and:
2379 // 1.) Layer 0 is latched
2380 // 2.) Layer 0 gets a new frame
2381 // 2.) Layer 1 gets a new frame
2382 // 3.) Layer 1 is latched.
2383 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2384 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002385 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002386 if (layer->hasQueuedFrame()) {
2387 frameQueued = true;
2388 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002389 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002390 } else {
2391 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002392 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002393 } else {
2394 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002395 }
Robert Carr2047fae2016-11-28 14:09:09 -08002396 });
2397
Dan Stoza9e56aa02015-11-02 13:00:03 -08002398 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002399 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002400 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002401 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002402 if (!dirty.isEmpty()) {
2403 newDataLatched = true;
2404 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002405 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002406
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002407 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002408
2409 // If we will need to wake up at some time in the future to deal with a
2410 // queued frame that shouldn't be displayed during this vsync period, wake
2411 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002413 signalLayerUpdate();
2414 }
2415
2416 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002417 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418}
2419
Mathias Agopianad456f92011-01-13 17:53:01 -08002420void SurfaceFlinger::invalidateHwcGeometry()
2421{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002422 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002423}
2424
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002425
Fabien Sanglard830b8472016-11-30 16:35:58 -08002426void SurfaceFlinger::doDisplayComposition(
2427 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002428 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002429{
Dan Stoza71433162014-02-04 16:22:36 -08002430 // We only need to actually compose the display if:
2431 // 1) It is being handled by hardware composer, which may need this to
2432 // keep its virtual display state machine in sync, or
2433 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002434 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002435 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002437 return;
2438 }
2439
Dan Stoza9e56aa02015-11-02 13:00:03 -08002440 ALOGV("doDisplayComposition");
2441
Mathias Agopian87baae12012-07-31 12:38:26 -07002442 Region dirtyRegion(inDirtyRegion);
2443
Mathias Agopianb8a55602009-06-26 19:06:36 -07002444 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002445 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446
Fabien Sanglard830b8472016-11-30 16:35:58 -08002447 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002448 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002449 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2450 // takes a rectangle, we must make sure to update that whole
2451 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002452 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002453 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002454 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002455 // We need to redraw the rectangle that will be updated
2456 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002457 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002458 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002459 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002460 } else {
2461 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002462 dirtyRegion.set(displayDevice->bounds());
2463 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464 }
2465 }
2466
Fabien Sanglard830b8472016-11-30 16:35:58 -08002467 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002469 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002470 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002471
2472 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002473 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474}
2475
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476bool SurfaceFlinger::doComposeSurfaces(
2477 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002478{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002480
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002482
2483 mat4 oldColorMatrix;
2484 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2485 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2486 if (applyColorMatrix) {
2487 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2488 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2489 }
2490
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2492 if (hasClientComposition) {
2493 ALOGV("hasClientComposition");
2494
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002495#ifdef USE_HWC2
2496 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
2497 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
2498#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002500 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002502 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002503
2504 // |mStateLock| not needed as we are on the main thread
2505 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002506 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2507 }
2508 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002509 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002510
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002511 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2513 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002514 // when using overlays, we assume a fully transparent framebuffer
2515 // NOTE: we could reduce how much we need to clear, for instance
2516 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002517 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002518 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002520 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002521 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002523
2524 // we remove the scissor part
2525 // we're left with the letterbox region
2526 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002528
2529 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002531
2532 // but limit it to the dirty region
2533 region.andSelf(dirty);
2534
Mathias Agopianb9494d52012-04-18 02:28:45 -07002535 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002536 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002537 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002538 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002539 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002540 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002541
Dan Stoza9e56aa02015-11-02 13:00:03 -08002542 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002543 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002544 // scissor on the main display. It should never be needed
2545 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 const Rect& bounds(displayDevice->getBounds());
2547 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002548 if (scissor != bounds) {
2549 // scissor doesn't match the screen's dimensions, so we
2550 // need to clear everything outside of it and enable
2551 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002552
Mathias Agopianf45c5102012-10-24 16:29:17 -07002553 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554 const uint32_t height = displayDevice->getHeight();
2555 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002556 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002557 }
2558 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002559 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002560
Mathias Agopian85d751c2012-08-29 16:59:24 -07002561 /*
2562 * and then, render the layers targeted at the framebuffer
2563 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002564
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 ALOGV("Rendering client layers");
2566 const Transform& displayTransform = displayDevice->getTransform();
2567 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002568 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 bool firstLayer = true;
2570 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2571 const Region clip(dirty.intersect(
2572 displayTransform.transform(layer->visibleRegion)));
2573 ALOGV("Layer: %s", layer->getName().string());
2574 ALOGV(" Composition type: %s",
2575 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002576 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 switch (layer->getCompositionType(hwcId)) {
2578 case HWC2::Composition::Cursor:
2579 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002580 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002581 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002582 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002583 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2584 layer->isOpaque(state) && (state.alpha == 1.0f)
2585 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002586 // never clear the very first layer since we're
2587 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002588 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002589 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002590 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002591 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 case HWC2::Composition::Client: {
2593 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002594 break;
2595 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002597 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002598 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 } else {
2600 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002601 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002603 }
2604 } else {
2605 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002607 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002609 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002611 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002612 }
2613 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002614
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002615 if (applyColorMatrix) {
2616 getRenderEngine().setupColorTransform(oldColorMatrix);
2617 }
2618
Mathias Agopianf45c5102012-10-24 16:29:17 -07002619 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002621 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622}
2623
Fabien Sanglard830b8472016-11-30 16:35:58 -08002624void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2625 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002626 RenderEngine& engine(getRenderEngine());
2627 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628}
2629
Dan Stoza7d89d062015-04-30 13:29:25 -07002630status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002631 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002632 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002633 const sp<Layer>& lbc,
2634 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002635{
Dan Stoza7d89d062015-04-30 13:29:25 -07002636 // add this layer to the current state list
2637 {
2638 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002639 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002640 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2641 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002642 return NO_MEMORY;
2643 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 if (parent == nullptr) {
2645 mCurrentState.layersSortedByZ.add(lbc);
2646 } else {
2647 parent->addChild(lbc);
2648 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002649 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002650 mLayersAdded = true;
2651 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002652 }
2653
Mathias Agopian96f08192010-06-02 23:28:45 -07002654 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002655 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002656
Dan Stoza7d89d062015-04-30 13:29:25 -07002657 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002658}
2659
Robert Carr9524cb32017-02-13 11:32:32 -08002660status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002661 Mutex::Autolock _l(mStateLock);
2662
Robert Carr1f0a16a2016-10-24 16:27:39 -07002663 const auto& p = layer->getParent();
2664 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2665 mCurrentState.layersSortedByZ.remove(layer);
2666
Robert Carr136e2f62017-02-08 17:54:29 -08002667 // As a matter of normal operation, the LayerCleaner will produce a second
2668 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2669 // so we will succeed in promoting it, but it's already been removed
2670 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2671 // otherwise something has gone wrong and we are leaking the layer.
2672 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002673 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2674 layer->getName().string(),
2675 (p != nullptr) ? p->getName().string() : "no-parent");
2676 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002677 } else if (index < 0) {
2678 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002679 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002680
2681 mLayersPendingRemoval.add(layer);
2682 mLayersRemoved = true;
2683 mNumLayers--;
2684 setTransactionFlags(eTransactionNeeded);
2685 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686}
2687
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002688uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002689 return android_atomic_release_load(&mTransactionFlags);
2690}
2691
Mathias Agopian3f844832013-08-07 21:24:32 -07002692uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2694}
2695
Mathias Agopian3f844832013-08-07 21:24:32 -07002696uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2698 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002699 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002700 }
2701 return old;
2702}
2703
Mathias Agopian8b33f032012-07-24 20:43:54 -07002704void SurfaceFlinger::setTransactionState(
2705 const Vector<ComposerState>& state,
2706 const Vector<DisplayState>& displays,
2707 uint32_t flags)
2708{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002709 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002710 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002711 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002712
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002713 if (flags & eAnimation) {
2714 // For window updates that are part of an animation we must wait for
2715 // previous animation "frames" to be handled.
2716 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002717 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002718 if (CC_UNLIKELY(err != NO_ERROR)) {
2719 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002720 // caller after a few seconds.
2721 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2722 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002723 mAnimTransactionPending = false;
2724 break;
2725 }
2726 }
2727 }
2728
Mathias Agopiane57f2922012-08-09 16:29:12 -07002729 size_t count = displays.size();
2730 for (size_t i=0 ; i<count ; i++) {
2731 const DisplayState& s(displays[i]);
2732 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002733 }
2734
Mathias Agopiane57f2922012-08-09 16:29:12 -07002735 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002736 for (size_t i=0 ; i<count ; i++) {
2737 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002738 // Here we need to check that the interface we're given is indeed
2739 // one of our own. A malicious client could give us a NULL
2740 // IInterface, or one of its own or even one of our own but a
2741 // different type. All these situations would cause us to crash.
2742 //
2743 // NOTE: it would be better to use RTTI as we could directly check
2744 // that we have a Client*. however, RTTI is disabled in Android.
2745 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002746 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002747 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002748 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002749 sp<Client> client( static_cast<Client *>(s.client.get()) );
2750 transactionFlags |= setClientStateLocked(client, s.state);
2751 }
2752 }
2753 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002754 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002755
Robert Carr2a7dbb42016-05-24 11:41:28 -07002756 // If a synchronous transaction is explicitly requested without any changes,
2757 // force a transaction anyway. This can be used as a flush mechanism for
2758 // previous async transactions.
2759 if (transactionFlags == 0 && (flags & eSynchronous)) {
2760 transactionFlags = eTransactionNeeded;
2761 }
2762
Mathias Agopian386aa982011-11-07 21:58:03 -08002763 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002764 if (mInterceptor.isEnabled()) {
2765 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2766 }
Irvel468051e2016-06-13 16:44:44 -07002767
Mathias Agopian386aa982011-11-07 21:58:03 -08002768 // this triggers the transaction
2769 setTransactionFlags(transactionFlags);
2770
2771 // if this is a synchronous transaction, wait for it to take effect
2772 // before returning.
2773 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002774 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002775 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002776 if (flags & eAnimation) {
2777 mAnimTransactionPending = true;
2778 }
2779 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002780 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2781 if (CC_UNLIKELY(err != NO_ERROR)) {
2782 // just in case something goes wrong in SF, return to the
2783 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002784 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2785 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002786 break;
2787 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002788 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 }
2790}
2791
Mathias Agopiane57f2922012-08-09 16:29:12 -07002792uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2793{
Jesse Hall9a143922012-10-04 16:29:19 -07002794 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2795 if (dpyIdx < 0)
2796 return 0;
2797
Mathias Agopiane57f2922012-08-09 16:29:12 -07002798 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002799 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002800 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002801 const uint32_t what = s.what;
2802 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002803 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002804 disp.surface = s.surface;
2805 flags |= eDisplayTransactionNeeded;
2806 }
2807 }
2808 if (what & DisplayState::eLayerStackChanged) {
2809 if (disp.layerStack != s.layerStack) {
2810 disp.layerStack = s.layerStack;
2811 flags |= eDisplayTransactionNeeded;
2812 }
2813 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002814 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002815 if (disp.orientation != s.orientation) {
2816 disp.orientation = s.orientation;
2817 flags |= eDisplayTransactionNeeded;
2818 }
2819 if (disp.frame != s.frame) {
2820 disp.frame = s.frame;
2821 flags |= eDisplayTransactionNeeded;
2822 }
2823 if (disp.viewport != s.viewport) {
2824 disp.viewport = s.viewport;
2825 flags |= eDisplayTransactionNeeded;
2826 }
2827 }
Michael Lentine47e45402014-07-18 15:34:25 -07002828 if (what & DisplayState::eDisplaySizeChanged) {
2829 if (disp.width != s.width) {
2830 disp.width = s.width;
2831 flags |= eDisplayTransactionNeeded;
2832 }
2833 if (disp.height != s.height) {
2834 disp.height = s.height;
2835 flags |= eDisplayTransactionNeeded;
2836 }
2837 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002838 }
2839 return flags;
2840}
2841
2842uint32_t SurfaceFlinger::setClientStateLocked(
2843 const sp<Client>& client,
2844 const layer_state_t& s)
2845{
2846 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002847 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002848 if (layer != 0) {
2849 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002850 bool geometryAppliesWithResize =
2851 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002852 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002853 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002854 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002855 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002856 }
2857 if (what & layer_state_t::eLayerChanged) {
2858 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 const auto& p = layer->getParent();
2860 if (p == nullptr) {
2861 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2862 if (layer->setLayer(s.z) && idx >= 0) {
2863 mCurrentState.layersSortedByZ.removeAt(idx);
2864 mCurrentState.layersSortedByZ.add(layer);
2865 // we need traversal (state changed)
2866 // AND transaction (list changed)
2867 flags |= eTransactionNeeded|eTraversalNeeded;
2868 }
2869 } else {
2870 if (p->setChildLayer(layer, s.z)) {
2871 flags |= eTransactionNeeded|eTraversalNeeded;
2872 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002873 }
2874 }
Robert Carrdb66e622017-04-10 16:55:57 -07002875 if (what & layer_state_t::eRelativeLayerChanged) {
2876 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2877 flags |= eTransactionNeeded|eTraversalNeeded;
2878 }
2879 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002880 if (what & layer_state_t::eSizeChanged) {
2881 if (layer->setSize(s.w, s.h)) {
2882 flags |= eTraversalNeeded;
2883 }
2884 }
2885 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002886 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002887 flags |= eTraversalNeeded;
2888 }
2889 if (what & layer_state_t::eMatrixChanged) {
2890 if (layer->setMatrix(s.matrix))
2891 flags |= eTraversalNeeded;
2892 }
2893 if (what & layer_state_t::eTransparentRegionChanged) {
2894 if (layer->setTransparentRegionHint(s.transparentRegion))
2895 flags |= eTraversalNeeded;
2896 }
Dan Stoza23116082015-06-18 14:58:39 -07002897 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002898 if (layer->setFlags(s.flags, s.mask))
2899 flags |= eTraversalNeeded;
2900 }
2901 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002902 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002903 flags |= eTraversalNeeded;
2904 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002905 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002906 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002907 flags |= eTraversalNeeded;
2908 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002909 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002910 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002911 // We only allow setting layer stacks for top level layers,
2912 // everything else inherits layer stack from its parent.
2913 if (layer->hasParent()) {
2914 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2915 layer->getName().string());
2916 } else if (idx < 0) {
2917 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2918 "that also does not appear in the top level layer list. Something"
2919 " has gone wrong.", layer->getName().string());
2920 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002921 mCurrentState.layersSortedByZ.removeAt(idx);
2922 mCurrentState.layersSortedByZ.add(layer);
2923 // we need traversal (state changed)
2924 // AND transaction (list changed)
2925 flags |= eTransactionNeeded|eTraversalNeeded;
2926 }
2927 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002928 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002929 if (s.barrierHandle != nullptr) {
2930 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2931 } else if (s.barrierGbp != nullptr) {
2932 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2933 if (authenticateSurfaceTextureLocked(gbp)) {
2934 const auto& otherLayer =
2935 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2936 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2937 } else {
2938 ALOGE("Attempt to defer transaction to to an"
2939 " unrecognized GraphicBufferProducer");
2940 }
2941 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002942 // We don't trigger a traversal here because if no other state is
2943 // changed, we don't want this to cause any more work
2944 }
Robert Carr1db73f62016-12-21 12:58:51 -08002945 if (what & layer_state_t::eReparentChildren) {
2946 if (layer->reparentChildren(s.reparentHandle)) {
2947 flags |= eTransactionNeeded|eTraversalNeeded;
2948 }
2949 }
Robert Carr9524cb32017-02-13 11:32:32 -08002950 if (what & layer_state_t::eDetachChildren) {
2951 layer->detachChildren();
2952 }
Robert Carrc3574f72016-03-24 12:19:32 -07002953 if (what & layer_state_t::eOverrideScalingModeChanged) {
2954 layer->setOverrideScalingMode(s.overrideScalingMode);
2955 // We don't trigger a traversal here because if no other state is
2956 // changed, we don't want this to cause any more work
2957 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958 }
2959 return flags;
2960}
2961
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002962status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002963 const String8& name,
2964 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002965 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002966 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2967 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002969 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002970 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002971 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002972 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002973 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002974
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002975 status_t result = NO_ERROR;
2976
2977 sp<Layer> layer;
2978
Cody Northropbc755282017-03-31 12:00:08 -06002979 String8 uniqueName = getUniqueLayerName(name);
2980
Mathias Agopian3165cc22012-08-08 19:42:09 -07002981 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2982 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002983 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002984 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002985 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002987 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002988 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06002989 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002990 handle, gbp, &layer);
2991 break;
2992 default:
2993 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002994 break;
2995 }
2996
Dan Stoza7d89d062015-04-30 13:29:25 -07002997 if (result != NO_ERROR) {
2998 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002999 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003000
Albert Chaulk479c60c2017-01-27 14:21:34 -05003001 layer->setInfo(windowType, ownerUid);
3002
Robert Carr1f0a16a2016-10-24 16:27:39 -07003003 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003004 if (result != NO_ERROR) {
3005 return result;
3006 }
Irvelffc9efc2016-07-27 15:16:37 -07003007 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003008
3009 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003010 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011}
3012
Cody Northropbc755282017-03-31 12:00:08 -06003013String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3014{
3015 bool matchFound = true;
3016 uint32_t dupeCounter = 0;
3017
3018 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3019 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3020
3021 // Loop over layers until we're sure there is no matching name
3022 while (matchFound) {
3023 matchFound = false;
3024 mDrawingState.traverseInZOrder([&](Layer* layer) {
3025 if (layer->getName() == uniqueName) {
3026 matchFound = true;
3027 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3028 }
3029 });
3030 }
3031
3032 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3033
3034 return uniqueName;
3035}
3036
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003037status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3038 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3039 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040{
3041 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003042 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 case PIXEL_FORMAT_TRANSPARENT:
3044 case PIXEL_FORMAT_TRANSLUCENT:
3045 format = PIXEL_FORMAT_RGBA_8888;
3046 break;
3047 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003048 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 break;
3050 }
3051
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003052 *outLayer = new Layer(this, client, name, w, h, flags);
3053 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3054 if (err == NO_ERROR) {
3055 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003056 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003058
3059 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3060 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061}
3062
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003063status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3064 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3065 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067 *outLayer = new LayerDim(this, client, name, w, h, flags);
3068 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003069 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003070 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003071}
3072
Mathias Agopianac9fa422013-02-11 16:40:36 -08003073status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074{
Robert Carr9524cb32017-02-13 11:32:32 -08003075 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003076 status_t err = NO_ERROR;
3077 sp<Layer> l(client->getLayerUser(handle));
3078 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003079 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003080 err = removeLayer(l);
3081 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3082 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003083 }
3084 return err;
3085}
3086
Mathias Agopian13127d82013-03-05 17:47:11 -08003087status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003088{
Mathias Agopian67106042013-03-14 19:18:13 -07003089 // called by ~LayerCleaner() when all references to the IBinder (handle)
3090 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003091 sp<Layer> l = layer.promote();
3092 if (l == nullptr) {
3093 // The layer has already been removed, carry on
3094 return NO_ERROR;
3095 } if (l->getParent() != nullptr) {
3096 // If we have a parent, then we can continue to live as long as it does.
3097 return NO_ERROR;
3098 }
3099 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100}
3101
Mathias Agopianb60314a2012-04-10 22:09:54 -07003102// ---------------------------------------------------------------------------
3103
Andy McFadden13a082e2012-08-24 10:16:42 -07003104void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003105 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003106 Vector<ComposerState> state;
3107 Vector<DisplayState> displays;
3108 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003109 d.what = DisplayState::eDisplayProjectionChanged |
3110 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003111 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003112 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003113 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003114 d.frame.makeInvalid();
3115 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003116 d.width = 0;
3117 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003118 displays.add(d);
3119 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003120 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003121
Dan Stoza9e56aa02015-11-02 13:00:03 -08003122 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3123 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003124 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003125
Brian Andersond0010582017-03-07 13:20:31 -08003126 // Use phase of 0 since phase is not known.
3127 // Use latency of 0, which will snap to the ideal latency.
3128 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003129}
3130
3131void SurfaceFlinger::initializeDisplays() {
3132 class MessageScreenInitialized : public MessageBase {
3133 SurfaceFlinger* flinger;
3134 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003135 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003136 virtual bool handler() {
3137 flinger->onInitializeDisplays();
3138 return true;
3139 }
3140 };
3141 sp<MessageBase> msg = new MessageScreenInitialized(this);
3142 postMessageAsync(msg); // we may be called from main thread, use async message
3143}
3144
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003145void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3146 int mode) {
3147 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3148 this);
3149 int32_t type = hw->getDisplayType();
3150 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003151
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003152 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003153 return;
3154 }
3155
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003156 hw->setPowerMode(mode);
3157 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3158 ALOGW("Trying to set power mode for virtual display");
3159 return;
3160 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003161
Irvelffc9efc2016-07-27 15:16:37 -07003162 if (mInterceptor.isEnabled()) {
3163 Mutex::Autolock _l(mStateLock);
3164 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3165 if (idx < 0) {
3166 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3167 return;
3168 }
3169 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3170 }
3171
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003172 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003173 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003174 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003175 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3176 // FIXME: eventthread only knows about the main display right now
3177 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003178 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003181 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003182 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003183 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003184
3185 struct sched_param param = {0};
3186 param.sched_priority = 1;
3187 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3188 ALOGW("Couldn't set SCHED_FIFO on display on");
3189 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003190 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003191 // Turn off the display
3192 struct sched_param param = {0};
3193 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3194 ALOGW("Couldn't set SCHED_OTHER on display off");
3195 }
3196
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003197 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003198 disableHardwareVsync(true); // also cancels any in-progress resync
3199
Mathias Agopiancde87a32012-09-13 14:09:01 -07003200 // FIXME: eventthread only knows about the main display right now
3201 mEventThread->onScreenReleased();
3202 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003203
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003204 getHwComposer().setPowerMode(type, mode);
3205 mVisibleRegionsDirty = true;
3206 // from this point on, SF will stop drawing on this display
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003207 } else if (mode == HWC_POWER_MODE_DOZE) {
3208 // Update display while dozing
3209 getHwComposer().setPowerMode(type, mode);
3210 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3211 // FIXME: eventthread only knows about the main display right now
3212 mEventThread->onScreenAcquired();
3213 resyncToHardwareVsync(true);
3214 }
3215 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3216 // Leave display going to doze
3217 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3218 disableHardwareVsync(true); // also cancels any in-progress resync
3219 // FIXME: eventthread only knows about the main display right now
3220 mEventThread->onScreenReleased();
3221 }
3222 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003223 } else {
3224 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003225 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003226}
3227
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003228void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3229 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003230 SurfaceFlinger& mFlinger;
3231 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003232 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003233 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003234 MessageSetPowerMode(SurfaceFlinger& flinger,
3235 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3236 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003237 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003238 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003239 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003240 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003241 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003242 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003243 ALOGW("Attempt to set power mode = %d for virtual display",
3244 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003245 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003246 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003247 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003248 return true;
3249 }
3250 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003251 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003252 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003253}
3254
3255// ---------------------------------------------------------------------------
3256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3258{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003259 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003260
Mathias Agopianbd115332013-04-18 16:41:04 -07003261 IPCThreadState* ipc = IPCThreadState::self();
3262 const int pid = ipc->getCallingPid();
3263 const int uid = ipc->getCallingUid();
3264 if ((uid != AID_SHELL) &&
3265 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003266 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003267 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003269 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003270 // (this would indicate SF is stuck, but we want to be able to
3271 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003272 status_t err = mStateLock.timedLock(s2ns(1));
3273 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003274 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003275 result.appendFormat(
3276 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3277 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003278 }
3279
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003280 bool dumpAll = true;
3281 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003282 size_t numArgs = args.size();
3283 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003284 if ((index < numArgs) &&
3285 (args[index] == String16("--list"))) {
3286 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003287 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003288 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003289 }
3290
3291 if ((index < numArgs) &&
3292 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003293 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003294 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003295 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003296 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003297
3298 if ((index < numArgs) &&
3299 (args[index] == String16("--latency-clear"))) {
3300 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003301 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003302 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003303 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003304
3305 if ((index < numArgs) &&
3306 (args[index] == String16("--dispsync"))) {
3307 index++;
3308 mPrimaryDispSync.dump(result);
3309 dumpAll = false;
3310 }
Dan Stozab90cf072015-03-05 11:05:59 -08003311
3312 if ((index < numArgs) &&
3313 (args[index] == String16("--static-screen"))) {
3314 index++;
3315 dumpStaticScreenStats(result);
3316 dumpAll = false;
3317 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003318
3319 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003320 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003321 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003322 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003323 dumpAll = false;
3324 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003325
3326 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3327 index++;
3328 dumpWideColorInfo(result);
3329 dumpAll = false;
3330 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003332
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003333 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003334 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003335 }
3336
Mathias Agopian9795c422009-08-26 16:36:26 -07003337 if (locked) {
3338 mStateLock.unlock();
3339 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340 }
3341 write(fd, result.string(), result.size());
3342 return NO_ERROR;
3343}
3344
Dan Stozac7014012014-02-14 15:03:43 -08003345void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3346 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003347{
Robert Carr2047fae2016-11-28 14:09:09 -08003348 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003349 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003350 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003351}
3352
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003353void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003354 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003355{
3356 String8 name;
3357 if (index < args.size()) {
3358 name = String8(args[index]);
3359 index++;
3360 }
3361
Dan Stoza9e56aa02015-11-02 13:00:03 -08003362 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3363 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003364 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003365
3366 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003367 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003368 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003369 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003370 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003371 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003372 }
Robert Carr2047fae2016-11-28 14:09:09 -08003373 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003374 }
3375}
3376
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003377void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003378 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003379{
3380 String8 name;
3381 if (index < args.size()) {
3382 name = String8(args[index]);
3383 index++;
3384 }
3385
Robert Carr2047fae2016-11-28 14:09:09 -08003386 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003387 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003388 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003389 }
Robert Carr2047fae2016-11-28 14:09:09 -08003390 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003391
Svetoslavd85084b2014-03-20 10:28:31 -07003392 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003393}
3394
Jamie Gennis6547ff42013-07-16 20:12:42 -07003395// This should only be called from the main thread. Otherwise it would need
3396// the lock and should use mCurrentState rather than mDrawingState.
3397void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003398 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003399 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003400 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003401
3402 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3403}
3404
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003405void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003406{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003407 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003408 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3409
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003410 if (isLayerTripleBufferingDisabled())
3411 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003412
3413 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003414 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003415 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003416 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003417 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3418 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003419 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003420}
3421
Dan Stozab90cf072015-03-05 11:05:59 -08003422void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3423{
3424 result.appendFormat("Static screen stats:\n");
3425 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3426 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3427 float percent = 100.0f *
3428 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3429 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3430 b + 1, bucketTimeSec, percent);
3431 }
3432 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3433 float percent = 100.0f *
3434 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3435 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3436 NUM_BUCKETS - 1, bucketTimeSec, percent);
3437}
3438
Dan Stozae77c7662016-05-13 11:37:28 -07003439void SurfaceFlinger::recordBufferingStats(const char* layerName,
3440 std::vector<OccupancyTracker::Segment>&& history) {
3441 Mutex::Autolock lock(mBufferingStatsMutex);
3442 auto& stats = mBufferingStats[layerName];
3443 for (const auto& segment : history) {
3444 if (!segment.usedThirdBuffer) {
3445 stats.twoBufferTime += segment.totalTime;
3446 }
3447 if (segment.occupancyAverage < 1.0f) {
3448 stats.doubleBufferedTime += segment.totalTime;
3449 } else if (segment.occupancyAverage < 2.0f) {
3450 stats.tripleBufferedTime += segment.totalTime;
3451 }
3452 ++stats.numSegments;
3453 stats.totalTime += segment.totalTime;
3454 }
3455}
3456
Brian Andersond6927fb2016-07-23 23:37:30 -07003457void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3458 result.appendFormat("Layer frame timestamps:\n");
3459
3460 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3461 const size_t count = currentLayers.size();
3462 for (size_t i=0 ; i<count ; i++) {
3463 currentLayers[i]->dumpFrameEvents(result);
3464 }
3465}
3466
Dan Stozae77c7662016-05-13 11:37:28 -07003467void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3468 result.append("Buffering stats:\n");
3469 result.append(" [Layer name] <Active time> <Two buffer> "
3470 "<Double buffered> <Triple buffered>\n");
3471 Mutex::Autolock lock(mBufferingStatsMutex);
3472 typedef std::tuple<std::string, float, float, float> BufferTuple;
3473 std::map<float, BufferTuple, std::greater<float>> sorted;
3474 for (const auto& statsPair : mBufferingStats) {
3475 const char* name = statsPair.first.c_str();
3476 const BufferingStats& stats = statsPair.second;
3477 if (stats.numSegments == 0) {
3478 continue;
3479 }
3480 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3481 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3482 stats.totalTime;
3483 float doubleBufferRatio = static_cast<float>(
3484 stats.doubleBufferedTime) / stats.totalTime;
3485 float tripleBufferRatio = static_cast<float>(
3486 stats.tripleBufferedTime) / stats.totalTime;
3487 sorted.insert({activeTime, {name, twoBufferRatio,
3488 doubleBufferRatio, tripleBufferRatio}});
3489 }
3490 for (const auto& sortedPair : sorted) {
3491 float activeTime = sortedPair.first;
3492 const BufferTuple& values = sortedPair.second;
3493 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3494 std::get<0>(values).c_str(), activeTime,
3495 std::get<1>(values), std::get<2>(values),
3496 std::get<3>(values));
3497 }
3498 result.append("\n");
3499}
3500
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003501void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3502 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3503
3504 // TODO: print out if wide-color mode is active or not
3505
3506 for (size_t d = 0; d < mDisplays.size(); d++) {
3507 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3508 int32_t hwcId = displayDevice->getHwcDisplayId();
3509 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3510 continue;
3511 }
3512
3513 result.appendFormat("Display %d color modes:\n", hwcId);
3514 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3515 for (auto&& mode : modes) {
3516 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3517 }
3518
3519 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3520 result.appendFormat(" Current color mode: %s (%d)\n",
3521 decodeColorMode(currentMode).c_str(), currentMode);
3522 }
3523 result.append("\n");
3524}
3525
Mathias Agopian74d211a2013-04-22 16:55:35 +02003526void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3527 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003528{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003529 bool colorize = false;
3530 if (index < args.size()
3531 && (args[index] == String16("--color"))) {
3532 colorize = true;
3533 index++;
3534 }
3535
3536 Colorizer colorizer(colorize);
3537
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003538 // figure out if we're stuck somewhere
3539 const nsecs_t now = systemTime();
3540 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3541 const nsecs_t inTransaction(mDebugInTransaction);
3542 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3543 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3544
3545 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003546 * Dump library configuration.
3547 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003548
3549 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003550 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003551 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003552 appendSfConfigString(result);
3553 appendUiConfigString(result);
3554 appendGuiConfigString(result);
3555 result.append("\n");
3556
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003557 result.append("\nWide-Color information:\n");
3558 dumpWideColorInfo(result);
3559
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003560 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003561 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003562 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003563 result.append(SyncFeatures::getInstance().toString());
3564 result.append("\n");
3565
Dan Stoza9e56aa02015-11-02 13:00:03 -08003566 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3567
Andy McFadden41d67d72014-04-25 16:58:34 -07003568 colorizer.bold(result);
3569 result.append("DispSync configuration: ");
3570 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003571 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003572 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003573 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003574 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003575 result.append("\n");
3576
Dan Stozab90cf072015-03-05 11:05:59 -08003577 // Dump static screen stats
3578 result.append("\n");
3579 dumpStaticScreenStats(result);
3580 result.append("\n");
3581
Dan Stozae77c7662016-05-13 11:37:28 -07003582 dumpBufferingStats(result);
3583
Andy McFadden4803b742012-09-24 19:07:20 -07003584 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003585 * Dump the visible layer list
3586 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003587 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003588 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003589 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003590 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003591 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003592 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003593
3594 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003595 * Dump Display state
3596 */
3597
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003598 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003599 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003600 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003601 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3602 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003603 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003604 }
3605
3606 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003607 * Dump SurfaceFlinger global state
3608 */
3609
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003610 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003611 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003612 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003613
Mathias Agopian888c8222012-08-04 21:10:38 -07003614 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003615 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003616
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003617 colorizer.bold(result);
3618 result.appendFormat("EGL implementation : %s\n",
3619 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3620 colorizer.reset(result);
3621 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003622 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003623
Mathias Agopian875d8e12013-06-07 15:35:48 -07003624 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003625
Mathias Agopian42977342012-08-05 00:40:46 -07003626 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003627 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3628 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003629 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003630 " last eglSwapBuffers() time: %f us\n"
3631 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003632 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003633 " refresh-rate : %f fps\n"
3634 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003635 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003636 " gpu_to_cpu_unsupported : %d\n"
3637 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638 mLastSwapBufferTime/1000.0,
3639 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003640 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003641 1e9 / activeConfig->getVsyncPeriod(),
3642 activeConfig->getDpiX(),
3643 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003644 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003645
Mathias Agopian74d211a2013-04-22 16:55:35 +02003646 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003647 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003648
Mathias Agopian74d211a2013-04-22 16:55:35 +02003649 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003650 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003651
3652 /*
3653 * VSYNC state
3654 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003655 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003656 result.append("\n");
3657
3658 /*
3659 * HWC layer minidump
3660 */
3661 for (size_t d = 0; d < mDisplays.size(); d++) {
3662 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3663 int32_t hwcId = displayDevice->getHwcDisplayId();
3664 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3665 continue;
3666 }
3667
3668 result.appendFormat("Display %d HWC layers:\n", hwcId);
3669 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003670 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003671 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003672 });
Dan Stozae22aec72016-08-01 13:20:59 -07003673 result.append("\n");
3674 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675
3676 /*
3677 * Dump HWComposer state
3678 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003679 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003680 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003681 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003682 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003683 result.appendFormat(" h/w composer %s\n",
3684 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003685 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003686
3687 /*
3688 * Dump gralloc state
3689 */
3690 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3691 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003692}
3693
Mathias Agopian13127d82013-03-05 17:47:11 -08003694const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003695SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003696 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003697 wp<IBinder> dpy;
3698 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3699 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3700 dpy = mDisplays.keyAt(i);
3701 break;
3702 }
3703 }
3704 if (dpy == NULL) {
3705 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3706 // Just use the primary display so we have something to return
3707 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3708 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003709 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003710}
3711
Keun young Park63f165f2012-08-31 10:53:36 -07003712bool SurfaceFlinger::startDdmConnection()
3713{
3714 void* libddmconnection_dso =
3715 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3716 if (!libddmconnection_dso) {
3717 return false;
3718 }
3719 void (*DdmConnection_start)(const char* name);
3720 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003721 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003722 if (!DdmConnection_start) {
3723 dlclose(libddmconnection_dso);
3724 return false;
3725 }
3726 (*DdmConnection_start)(getServiceName());
3727 return true;
3728}
3729
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003730status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731 switch (code) {
3732 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003733 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003734 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003735 case CLEAR_ANIMATION_FRAME_STATS:
3736 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003737 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003738 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739 {
3740 // codes that require permission check
3741 IPCThreadState* ipc = IPCThreadState::self();
3742 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003743 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003744 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003745 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003746 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003747 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003749 break;
3750 }
Robert Carr1db73f62016-12-21 12:58:51 -08003751 /*
3752 * Calling setTransactionState is safe, because you need to have been
3753 * granted a reference to Client* and Handle* to do anything with it.
3754 *
3755 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3756 */
3757 case SET_TRANSACTION_STATE:
3758 case CREATE_SCOPED_CONNECTION:
3759 {
3760 return OK;
3761 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003762 case CAPTURE_SCREEN:
3763 {
3764 // codes that require permission check
3765 IPCThreadState* ipc = IPCThreadState::self();
3766 const int pid = ipc->getCallingPid();
3767 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003768 if ((uid != AID_GRAPHICS) &&
3769 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003770 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003771 return PERMISSION_DENIED;
3772 }
3773 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003774 }
3775 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003776 return OK;
3777}
3778
3779status_t SurfaceFlinger::onTransact(
3780 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3781{
3782 status_t credentialCheck = CheckTransactCodeCredentials(code);
3783 if (credentialCheck != OK) {
3784 return credentialCheck;
3785 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3788 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003789 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003790 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003791 IPCThreadState* ipc = IPCThreadState::self();
3792 const int pid = ipc->getCallingPid();
3793 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003794 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003795 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 return PERMISSION_DENIED;
3797 }
3798 int n;
3799 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003800 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003801 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003802 return NO_ERROR;
3803 case 1002: // SHOW_UPDATES
3804 n = data.readInt32();
3805 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003806 invalidateHwcGeometry();
3807 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003809 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003810 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003811 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003812 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003813 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003814 setTransactionFlags(
3815 eTransactionNeeded|
3816 eDisplayTransactionNeeded|
3817 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003818 return NO_ERROR;
3819 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003820 case 1006:{ // send empty update
3821 signalRefresh();
3822 return NO_ERROR;
3823 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003824 case 1008: // toggle use of hw composer
3825 n = data.readInt32();
3826 mDebugDisableHWC = n ? 1 : 0;
3827 invalidateHwcGeometry();
3828 repaintEverything();
3829 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003830 case 1009: // toggle use of transform hint
3831 n = data.readInt32();
3832 mDebugDisableTransformHint = n ? 1 : 0;
3833 invalidateHwcGeometry();
3834 repaintEverything();
3835 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003837 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003838 reply->writeInt32(0);
3839 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003840 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003841 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 return NO_ERROR;
3843 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003844 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003845 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003846 return NO_ERROR;
3847 }
3848 case 1014: {
3849 // daltonize
3850 n = data.readInt32();
3851 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003852 case 1:
3853 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3854 break;
3855 case 2:
3856 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3857 break;
3858 case 3:
3859 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3860 break;
3861 default:
3862 mDaltonizer.setType(ColorBlindnessType::None);
3863 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003864 }
3865 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003866 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003867 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003868 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003869 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003870 invalidateHwcGeometry();
3871 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003872 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003874 case 1015: {
3875 // apply a color matrix
3876 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003877 if (n) {
3878 // color matrix is sent as mat3 matrix followed by vec3
3879 // offset, then packed into a mat4 where the last row is
3880 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003881 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003882 for (size_t j = 0; j < 4; j++) {
3883 mColorMatrix[i][j] = data.readFloat();
3884 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003885 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003886 } else {
3887 mColorMatrix = mat4();
3888 }
3889 invalidateHwcGeometry();
3890 repaintEverything();
3891 return NO_ERROR;
3892 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003893 // This is an experimental interface
3894 // Needs to be shifted to proper binder interface when we productize
3895 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003896 n = data.readInt32();
3897 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003898 return NO_ERROR;
3899 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003900 case 1017: {
3901 n = data.readInt32();
3902 mForceFullDamage = static_cast<bool>(n);
3903 return NO_ERROR;
3904 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003905 case 1018: { // Modify Choreographer's phase offset
3906 n = data.readInt32();
3907 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3908 return NO_ERROR;
3909 }
3910 case 1019: { // Modify SurfaceFlinger's phase offset
3911 n = data.readInt32();
3912 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3913 return NO_ERROR;
3914 }
Irvel468051e2016-06-13 16:44:44 -07003915 case 1020: { // Layer updates interceptor
3916 n = data.readInt32();
3917 if (n) {
3918 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003919 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003920 }
3921 else{
3922 ALOGV("Interceptor disabled");
3923 mInterceptor.disable();
3924 }
3925 return NO_ERROR;
3926 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003927 case 1021: { // Disable HWC virtual displays
3928 n = data.readInt32();
3929 mUseHwcVirtualDisplays = !n;
3930 return NO_ERROR;
3931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 }
3933 }
3934 return err;
3935}
3936
Mathias Agopian53331da2011-08-22 21:44:41 -07003937void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003938 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003939 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003940}
3941
Mathias Agopian59119e62010-10-11 12:37:43 -07003942// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003943// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003944// ---------------------------------------------------------------------------
3945
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003946/* The code below is here to handle b/8734824
3947 *
3948 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003949 * from the surfaceflinger thread to the calling binder thread, where they
3950 * are executed. This allows the calling thread in the calling process to be
3951 * reused and not depend on having "enough" binder threads to handle the
3952 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003953 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003954class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003955 /* Parts of GraphicProducerWrapper are run on two different threads,
3956 * communicating by sending messages via Looper but also by shared member
3957 * data. Coherence maintenance is subtle and in places implicit (ugh).
3958 *
3959 * Don't rely on Looper's sendMessage/handleMessage providing
3960 * release/acquire semantics for any data not actually in the Message.
3961 * Data going from surfaceflinger to binder threads needs to be
3962 * synchronized explicitly.
3963 *
3964 * Barrier open/wait do provide release/acquire semantics. This provides
3965 * implicit synchronization for data coming back from binder to
3966 * surfaceflinger threads.
3967 */
3968
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003969 sp<IGraphicBufferProducer> impl;
3970 sp<Looper> looper;
3971 status_t result;
3972 bool exitPending;
3973 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003974 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003975 uint32_t code;
3976 Parcel const* data;
3977 Parcel* reply;
3978
3979 enum {
3980 MSG_API_CALL,
3981 MSG_EXIT
3982 };
3983
3984 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003985 * Called on surfaceflinger thread. This is called by our "fake"
3986 * BpGraphicBufferProducer. We package the data and reply Parcel and
3987 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003988 */
3989 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003990 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003991 this->code = code;
3992 this->data = &data;
3993 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003994 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003995 // if we've exited, we run the message synchronously right here.
3996 // note (JH): as far as I can tell from looking at the code, this
3997 // never actually happens. if it does, i'm not sure if it happens
3998 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003999 handleMessage(Message(MSG_API_CALL));
4000 } else {
4001 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004002 // Prevent stores to this->{code, data, reply} from being
4003 // reordered later than the construction of Message.
4004 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004005 looper->sendMessage(this, Message(MSG_API_CALL));
4006 barrier.wait();
4007 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004008 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004009 }
4010
4011 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004012 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004013 * call the real BpGraphicBufferProducer.
4014 */
4015 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004016 int what = message.what;
4017 // Prevent reads below from happening before the read from Message
4018 atomic_thread_fence(memory_order_acquire);
4019 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004020 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004021 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004022 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004023 exitRequested = true;
4024 }
4025 }
4026
4027public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004028 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004029 : impl(impl),
4030 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004031 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004032 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004033 exitRequested(false),
4034 code(0),
4035 data(NULL),
4036 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004037 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004038
Jesse Hallb154c422014-07-13 12:47:02 -07004039 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004040 status_t waitForResponse() {
4041 do {
4042 looper->pollOnce(-1);
4043 } while (!exitRequested);
4044 return result;
4045 }
4046
Jesse Hallb154c422014-07-13 12:47:02 -07004047 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004048 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004049 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004050 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004051 // Ensure this->result is visible to the binder thread before it
4052 // handles the message.
4053 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004054 looper->sendMessage(this, Message(MSG_EXIT));
4055 }
4056};
4057
4058
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004059status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4060 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004061 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004062 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004063 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004064
4065 if (CC_UNLIKELY(display == 0))
4066 return BAD_VALUE;
4067
4068 if (CC_UNLIKELY(producer == 0))
4069 return BAD_VALUE;
4070
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004071 // if we have secure windows on this display, never allow the screen capture
4072 // unless the producer interface is local (i.e.: we can take a screenshot for
4073 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004074 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004075
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004076 // Convert to surfaceflinger's internal rotation type.
4077 Transform::orientation_flags rotationFlags;
4078 switch (rotation) {
4079 case ISurfaceComposer::eRotateNone:
4080 rotationFlags = Transform::ROT_0;
4081 break;
4082 case ISurfaceComposer::eRotate90:
4083 rotationFlags = Transform::ROT_90;
4084 break;
4085 case ISurfaceComposer::eRotate180:
4086 rotationFlags = Transform::ROT_180;
4087 break;
4088 case ISurfaceComposer::eRotate270:
4089 rotationFlags = Transform::ROT_270;
4090 break;
4091 default:
4092 rotationFlags = Transform::ROT_0;
4093 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4094 break;
4095 }
4096
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004097 class MessageCaptureScreen : public MessageBase {
4098 SurfaceFlinger* flinger;
4099 sp<IBinder> display;
4100 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004101 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004102 uint32_t reqWidth, reqHeight;
4103 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004104 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004105 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004106 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004107 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004108 public:
4109 MessageCaptureScreen(SurfaceFlinger* flinger,
4110 const sp<IBinder>& display,
4111 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004112 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004113 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004114 bool useIdentityTransform,
4115 Transform::orientation_flags rotation,
4116 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004117 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004118 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004119 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004120 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004121 rotation(rotation), result(PERMISSION_DENIED),
4122 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004123 {
4124 }
4125 status_t getResult() const {
4126 return result;
4127 }
4128 virtual bool handler() {
4129 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004130 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004131 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004132 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004133 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004134 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004135 return true;
4136 }
4137 };
4138
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004139 // this creates a "fake" BBinder which will serve as a "fake" remote
4140 // binder to receive the marshaled calls and forward them to the
4141 // real remote (a BpGraphicBufferProducer)
4142 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4143
4144 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4145 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004146 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004147 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004148 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004149 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004150
4151 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004152 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004153 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004154 }
4155 return res;
4156}
4157
Mathias Agopian180f10d2013-04-10 22:55:41 -07004158
4159void SurfaceFlinger::renderScreenImplLocked(
4160 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004161 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004162 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004163 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004164{
4165 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004166 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004167
4168 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004169 const int32_t hw_w = hw->getWidth();
4170 const int32_t hw_h = hw->getHeight();
4171 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004172 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004173
Dan Stozac1879002014-05-22 15:59:05 -07004174 // if a default or invalid sourceCrop is passed in, set reasonable values
4175 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4176 !sourceCrop.isValid()) {
4177 sourceCrop.setLeftTop(Point(0, 0));
4178 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4179 }
4180
4181 // ensure that sourceCrop is inside screen
4182 if (sourceCrop.left < 0) {
4183 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4184 }
Dan Stozabe31f442014-06-11 11:20:54 -07004185 if (sourceCrop.right > hw_w) {
4186 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004187 }
4188 if (sourceCrop.top < 0) {
4189 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4190 }
Dan Stozabe31f442014-06-11 11:20:54 -07004191 if (sourceCrop.bottom > hw_h) {
4192 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004193 }
4194
Mathias Agopian180f10d2013-04-10 22:55:41 -07004195 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004196 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004197
4198 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004199 engine.setViewportAndProjection(
4200 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004201 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004202
4203 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004204 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004205
Robert Carr1f0a16a2016-10-24 16:27:39 -07004206 // We loop through the first level of layers without traversing,
4207 // as we need to interpret min/max layer Z in the top level Z space.
4208 for (const auto& layer : mDrawingState.layersSortedByZ) {
4209 if (layer->getLayerStack() != hw->getLayerStack()) {
4210 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004211 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004212 const Layer::State& state(layer->getDrawingState());
4213 if (state.z < minLayerZ || state.z > maxLayerZ) {
4214 continue;
4215 }
4216 layer->traverseInZOrder([&](Layer* layer) {
4217 if (!layer->isVisible()) {
4218 return;
4219 }
4220 if (filtering) layer->setFiltering(true);
4221 layer->draw(hw, useIdentityTransform);
4222 if (filtering) layer->setFiltering(false);
4223 });
4224 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004225
Mathias Agopian931bda12013-08-28 18:11:46 -07004226 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004227}
4228
4229
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004230status_t SurfaceFlinger::captureScreenImplLocked(
4231 const sp<const DisplayDevice>& hw,
4232 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004233 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004234 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004235 bool useIdentityTransform, Transform::orientation_flags rotation,
4236 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004237{
4238 ATRACE_CALL();
4239
Mathias Agopian180f10d2013-04-10 22:55:41 -07004240 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004241 uint32_t hw_w = hw->getWidth();
4242 uint32_t hw_h = hw->getHeight();
4243
4244 if (rotation & Transform::ROT_90) {
4245 std::swap(hw_w, hw_h);
4246 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004247
Mathias Agopian180f10d2013-04-10 22:55:41 -07004248 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4249 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4250 reqWidth, reqHeight, hw_w, hw_h);
4251 return BAD_VALUE;
4252 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004253
Mathias Agopian180f10d2013-04-10 22:55:41 -07004254 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4255 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4256
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004257 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004258 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004259 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004260 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4261 (state.z < minLayerZ || state.z > maxLayerZ)) {
4262 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004263 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004264 layer->traverseInZOrder([&](Layer *layer) {
4265 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4266 layer->isSecure());
4267 });
4268 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004269
4270 if (!isLocalScreenshot && secureLayerIsVisible) {
4271 ALOGW("FB is protected: PERMISSION_DENIED");
4272 return PERMISSION_DENIED;
4273 }
4274
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004275 // create a surface (because we're a producer, and we need to
4276 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004277 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004278
4279 // Put the screenshot Surface into async mode so that
4280 // Layer::headFenceHasSignaled will always return true and we'll latch the
4281 // first buffer regardless of whether or not its acquire fence has
4282 // signaled. This is needed to avoid a race condition in the rotation
4283 // animation. See b/30209608
4284 sur->setAsyncMode(true);
4285
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004286 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004287
Michael Lentine5a16a622015-05-21 13:48:24 -07004288 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4289 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004290 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4291 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004292
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004293 int err = 0;
4294 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004295 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004296 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4297 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004298
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004299 if (err == NO_ERROR) {
4300 ANativeWindowBuffer* buffer;
4301 /* TODO: Once we have the sync framework everywhere this can use
4302 * server-side waits on the fence that dequeueBuffer returns.
4303 */
4304 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4305 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004306 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004307 // create an EGLImage from the buffer so we can later
4308 // turn it into a texture
4309 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4310 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4311 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004312 // this binds the given EGLImage as a framebuffer for the
4313 // duration of this scope.
4314 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4315 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004316 // this will in fact render into our dequeued buffer
4317 // via an FBO, which means we didn't have to create
4318 // an EGLSurface and therefore we're not
4319 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004320 renderScreenImplLocked(
4321 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4322 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004323
Riley Andrews86639902014-08-15 12:27:24 -07004324 // Attempt to create a sync khr object that can produce a sync point. If that
4325 // isn't available, create a non-dupable sync object in the fallback path and
4326 // wait on it directly.
4327 EGLSyncKHR sync;
4328 if (!DEBUG_SCREENSHOTS) {
4329 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004330 // native fence fd will not be populated until flush() is done.
4331 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004332 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004333 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004334 }
Riley Andrews86639902014-08-15 12:27:24 -07004335 if (sync != EGL_NO_SYNC_KHR) {
4336 // get the sync fd
4337 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4338 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4339 ALOGW("captureScreen: failed to dup sync khr object");
4340 syncFd = -1;
4341 }
4342 eglDestroySyncKHR(mEGLDisplay, sync);
4343 } else {
4344 // fallback path
4345 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4346 if (sync != EGL_NO_SYNC_KHR) {
4347 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4348 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4349 EGLint eglErr = eglGetError();
4350 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4351 ALOGW("captureScreen: fence wait timed out");
4352 } else {
4353 ALOGW_IF(eglErr != EGL_SUCCESS,
4354 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4355 }
4356 eglDestroySyncKHR(mEGLDisplay, sync);
4357 } else {
4358 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4359 }
4360 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004361 if (DEBUG_SCREENSHOTS) {
4362 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4363 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4364 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4365 hw, minLayerZ, maxLayerZ);
4366 delete [] pixels;
4367 }
4368
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004369 } else {
4370 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4371 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004372 window->cancelBuffer(window, buffer, syncFd);
4373 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004374 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004375 // destroy our image
4376 eglDestroyImageKHR(mEGLDisplay, image);
4377 } else {
4378 result = BAD_VALUE;
4379 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004380 if (buffer) {
4381 // queueBuffer takes ownership of syncFd
4382 result = window->queueBuffer(window, buffer, syncFd);
4383 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004384 }
4385 } else {
4386 result = BAD_VALUE;
4387 }
4388 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4389 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004390
Mathias Agopian74c40c02010-09-29 13:02:36 -07004391 return result;
4392}
4393
Mathias Agopiand5556842013-09-19 17:08:37 -07004394void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004395 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004396 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004397 for (size_t y=0 ; y<h ; y++) {
4398 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4399 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004400 if (p[x] != 0xFF000000) return;
4401 }
4402 }
4403 ALOGE("*** we just took a black screenshot ***\n"
4404 "requested minz=%d, maxz=%d, layerStack=%d",
4405 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004406
Robert Carr2047fae2016-11-28 14:09:09 -08004407 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004408 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004409 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004410 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4411 state.z <= maxLayerZ) {
4412 layer->traverseInZOrder([&](Layer* layer) {
4413 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4414 layer->isVisible() ? '+' : '-',
4415 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004416 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004417 i++;
4418 });
4419 }
4420 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004421 }
4422}
4423
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004424// ---------------------------------------------------------------------------
4425
Robert Carr2047fae2016-11-28 14:09:09 -08004426void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4427 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004428}
4429
Robert Carr2047fae2016-11-28 14:09:09 -08004430void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4431 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004432}
4433
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004434}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004435
4436
4437#if defined(__gl_h_)
4438#error "don't include gl/gl.h in this file"
4439#endif
4440
4441#if defined(__gl2_h_)
4442#error "don't include gl2/gl2.h in this file"
4443#endif