blob: 46f5a1fbf3341e1893c52858ca7283e137dcf6c0 [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
Mathias Agopianc666cae2012-07-25 18:56:13 -070040#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070041#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.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"
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080076#include "VrStateCallbacks.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
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
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700105// This is the phase offset in nanoseconds of the software vsync event
106// relative to the vsync event reported by HWComposer. The software vsync
107// event is when SurfaceFlinger and Choreographer-based applications run each
108// frame.
109//
110// This phase offset allows adjustment of the minimum latency from application
111// wake-up (by Choregographer) time to the time at which the resulting window
112// image is displayed. This value may be either positive (after the HW vsync)
113// or negative (before the HW vsync). Setting it to 0 will result in a
114// minimum latency of two vsync periods because the app and SurfaceFlinger
115// will run just after the HW vsync. Setting it to a positive number will
116// result in the minimum latency being:
117//
118// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
119//
120// Note that reducing this latency makes it more likely for the applications
121// to not have their window content image ready in time. When this happens
122// the latency will end up being an additional vsync period, and animations
123// will hiccup. Therefore, this latency should be tuned somewhat
124// conservatively (or at least with awareness of the trade-off being made).
Jaesoo Lee43518572017-01-23 19:03:16 +0900125static int64_t vsyncPhaseOffsetNs = getInt64<
126 ISurfaceFlingerConfigs,
127 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700129// This is the phase offset at which SurfaceFlinger's composition runs.
Brian Anderson0a61b0c2016-12-07 14:55:56 -0800130static constexpr int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132// ---------------------------------------------------------------------------
133
Mathias Agopian99b49842011-06-27 16:05:52 -0700134const String16 sHardwareTest("android.permission.HARDWARE_TEST");
135const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
136const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
137const String16 sDump("android.permission.DUMP");
138
139// ---------------------------------------------------------------------------
140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700142 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700144 mTransactionPending(false),
145 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700146 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700147 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800149 mHwc(nullptr),
150 mRealHwc(nullptr),
151 mVrHwc(nullptr),
152 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800156 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800157 mAnimCompositionPending(false),
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800158 mVrModeSupported(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800159 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700160 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700161 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700162 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700163 mDebugInSwapBuffers(0),
164 mLastSwapBufferTime(0),
165 mDebugInTransaction(0),
166 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700167 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700168 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800169 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000170 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700171 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700172 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800173 mHasColorMatrix(false),
174 mHasPoweredOff(false),
175 mFrameBuckets(),
176 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700177 mLastSwapTime(0),
Mark Urbanus209beca2017-02-23 11:16:04 -0800178 mNumLayers(0)
179#ifdef USE_HWC2
180 ,mEnterVrMode(false)
181#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182{
Steve Blocka19954a2012-01-04 20:05:49 +0000183 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184
185 // debugging stuff...
186 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700187
Mark Urbanus3a8f7942017-03-02 15:44:10 -0800188 // TODO (urbanus): remove once b/35319396 is fixed.
189 property_get("ro.boot.vr", value, "0");
190 mVrModeSupported = atoi(value);
191
Mathias Agopianb4b17302013-03-20 18:36:41 -0700192 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700193 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195 property_get("debug.sf.showupdates", value, "0");
196 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700197
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700198 property_get("debug.sf.ddms", value, "0");
199 mDebugDDMS = atoi(value);
200 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700201 if (!startDdmConnection()) {
202 // start failed, and DDMS debugging not enabled
203 mDebugDDMS = 0;
204 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700206 ALOGI_IF(mDebugRegion, "showupdates enabled");
207 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700208
209 property_get("debug.sf.disable_backpressure", value, "0");
210 mPropagateBackpressure = !atoi(value);
211 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700212
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800213 property_get("debug.sf.enable_hwc_vds", value, "0");
214 mUseHwcVirtualDisplays = atoi(value);
215 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800216
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800217 property_get("ro.sf.disable_triple_buffer", value, "1");
218 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800219 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220}
221
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800222void SurfaceFlinger::onFirstRef()
223{
224 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800225}
226
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227SurfaceFlinger::~SurfaceFlinger()
228{
Mathias Agopiana4912602012-07-12 14:25:33 -0700229 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
230 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
231 eglTerminate(display);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800232
233 if (mVrStateCallbacks.get()) {
234 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
235 defaultServiceManager()->checkService(String16("vrmanager")));
236 if (vrManagerService.get()) {
237 vrManagerService->unregisterListener(mVrStateCallbacks);
238 }
239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
Jamie Gennis9a78c902011-01-12 18:30:40 -0800343sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
344{
345 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
346 return gba;
347}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700348
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800349void SurfaceFlinger::bootFinished()
350{
Wei Wangb254fa32017-01-31 17:43:23 -0800351 if (mStartBootAnimThread->join() != NO_ERROR) {
352 ALOGE("Join StartBootAnimThread failed!");
353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800354 const nsecs_t now = systemTime();
355 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000356 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700357 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358
359 // wait patiently for the window manager death
360 const String16 name("window");
361 sp<IBinder> window(defaultServiceManager()->getService(name));
362 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700363 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 }
365
366 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700367 // formerly we would just kill the process, but we now ask it to exit so it
368 // can choose where to stop the animation.
369 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700370
371 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
372 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
373 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800374
375 sp<IVrManager> vrManagerService = interface_cast<IVrManager>(
376 defaultServiceManager()->checkService(String16("vrmanager")));
377 if (vrManagerService.get()) {
378 mVrStateCallbacks = new VrStateCallbacks(*this);
379 vrManagerService->registerListener(mVrStateCallbacks);
380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopian3f844832013-08-07 21:24:32 -0700383void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700385 RenderEngine& engine;
386 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700388 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
389 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700390 }
391 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700392 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700393 return true;
394 }
395 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700396 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700397}
398
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700399class DispSyncSource : public VSyncSource, private DispSync::Callback {
400public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700401 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000402 const char* name) :
403 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700404 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700405 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000406 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
407 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700408 mDispSync(dispSync),
409 mCallbackMutex(),
410 mCallback(),
411 mVsyncMutex(),
412 mPhaseOffset(phaseOffset),
413 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700414
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 virtual ~DispSyncSource() {}
416
417 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700418 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000420 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 static_cast<DispSync::Callback*>(this));
422 if (err != NO_ERROR) {
423 ALOGE("error registering vsync callback: %s (%d)",
424 strerror(-err), err);
425 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700426 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 } else {
428 status_t err = mDispSync->removeEventListener(
429 static_cast<DispSync::Callback*>(this));
430 if (err != NO_ERROR) {
431 ALOGE("error unregistering vsync callback: %s (%d)",
432 strerror(-err), err);
433 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700434 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 }
438
439 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700440 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441 mCallback = callback;
442 }
443
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700444 virtual void setPhaseOffset(nsecs_t phaseOffset) {
445 Mutex::Autolock lock(mVsyncMutex);
446
447 // Normalize phaseOffset to [0, period)
448 auto period = mDispSync->getPeriod();
449 phaseOffset %= period;
450 if (phaseOffset < 0) {
451 // If we're here, then phaseOffset is in (-period, 0). After this
452 // operation, it will be in (0, period)
453 phaseOffset += period;
454 }
455 mPhaseOffset = phaseOffset;
456
457 // If we're not enabled, we don't need to mess with the listeners
458 if (!mEnabled) {
459 return;
460 }
461
462 // Remove the listener with the old offset
463 status_t err = mDispSync->removeEventListener(
464 static_cast<DispSync::Callback*>(this));
465 if (err != NO_ERROR) {
466 ALOGE("error unregistering vsync callback: %s (%d)",
467 strerror(-err), err);
468 }
469
470 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000471 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700472 static_cast<DispSync::Callback*>(this));
473 if (err != NO_ERROR) {
474 ALOGE("error registering vsync callback: %s (%d)",
475 strerror(-err), err);
476 }
477 }
478
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479private:
480 virtual void onDispSyncEvent(nsecs_t when) {
481 sp<VSyncSource::Callback> callback;
482 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700483 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 callback = mCallback;
485
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700486 if (mTraceVsync) {
487 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700488 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700489 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 }
491
492 if (callback != NULL) {
493 callback->onVSyncEvent(when);
494 }
495 }
496
Tim Murray4a4e4a22016-04-19 16:29:23 +0000497 const char* const mName;
498
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499 int mValue;
500
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700501 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700502 const String8 mVsyncOnLabel;
503 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700504
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700505 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700506
507 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700509
510 Mutex mVsyncMutex; // Protects the following
511 nsecs_t mPhaseOffset;
512 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700513};
514
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700515class InjectVSyncSource : public VSyncSource {
516public:
517 InjectVSyncSource() {}
518
519 virtual ~InjectVSyncSource() {}
520
521 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
522 std::lock_guard<std::mutex> lock(mCallbackMutex);
523 mCallback = callback;
524 }
525
526 virtual void onInjectSyncEvent(nsecs_t when) {
527 std::lock_guard<std::mutex> lock(mCallbackMutex);
528 mCallback->onVSyncEvent(when);
529 }
530
531 virtual void setVSyncEnabled(bool) {}
532 virtual void setPhaseOffset(nsecs_t) {}
533
534private:
535 std::mutex mCallbackMutex; // Protects the following
536 sp<VSyncSource::Callback> mCallback;
537};
538
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700539void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700540 ALOGI( "SurfaceFlinger's main thread ready to run. "
541 "Initializing graphics H/W...");
542
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900543 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
544
Dan Stoza9e56aa02015-11-02 13:00:03 -0800545 { // Autolock scope
546 Mutex::Autolock _l(mStateLock);
547
548 // initialize EGL for the default display
549 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
550 eglInitialize(mEGLDisplay, NULL, NULL);
551
552 // start the EventThread
553 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
554 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700555 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
557 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700558 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800559 mEventQueue.setEventThread(mSFEventThread);
560
Tim Murrayacff43d2016-07-29 13:57:24 -0700561 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700562 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700563 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700564 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
565 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
566 }
567
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 // Get a RenderEngine for the given display / config (can't fail)
569 mRenderEngine = RenderEngine::create(mEGLDisplay,
570 HAL_PIXEL_FORMAT_RGBA_8888);
571 }
572
573 // Drop the state lock while we initialize the hardware composer. We drop
574 // the lock because on creation, it will call back into SurfaceFlinger to
575 // initialize the primary display.
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800576 LOG_ALWAYS_FATAL_IF(mEnterVrMode, "Starting in vr mode is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800577 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800578 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
580
Jesse Hall692c7232012-11-08 15:41:56 -0800581 Mutex::Autolock _l(mStateLock);
582
Mathias Agopian875d8e12013-06-07 15:35:48 -0700583 // retrieve the EGL context that was selected/created
584 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700585
Mathias Agopianda27af92012-09-13 18:17:13 -0700586 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
587 "couldn't create EGLContext");
588
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 // make the GLContext current so that we can create textures when creating
590 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700591 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
592
Jamie Gennisd1700752013-10-14 12:22:52 -0700593 mEventControlThread = new EventControlThread(this);
594 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
595
Mathias Agopian92a979a2012-08-02 18:32:23 -0700596 // initialize our drawing state
597 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700598
Andy McFadden13a082e2012-08-24 10:16:42 -0700599 // set initial conditions (e.g. unblank default device)
600 initializeDisplays();
601
Dan Stoza4e637772016-07-28 13:31:51 -0700602 mRenderEngine->primeCache();
603
Wei Wangb254fa32017-01-31 17:43:23 -0800604 mStartBootAnimThread = new StartBootAnimThread();
605 if (mStartBootAnimThread->Start() != NO_ERROR) {
606 ALOGE("Run StartBootAnimThread failed!");
607 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800608
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700610}
611
Mathias Agopiana67e4182012-06-19 17:26:12 -0700612void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800613 // Start boot animation service by setting a property mailbox
614 // if property setting thread is already running, Start() will be just a NOP
615 mStartBootAnimThread->Start();
616 // Wait until property was set
617 if (mStartBootAnimThread->join() != NO_ERROR) {
618 ALOGE("Join StartBootAnimThread failed!");
619 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700620}
621
Mathias Agopian875d8e12013-06-07 15:35:48 -0700622size_t SurfaceFlinger::getMaxTextureSize() const {
623 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700624}
625
Mathias Agopian875d8e12013-06-07 15:35:48 -0700626size_t SurfaceFlinger::getMaxViewportDims() const {
627 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700628}
629
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800630// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800631
Jamie Gennis582270d2011-08-17 18:19:00 -0700632bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800633 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800634 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800635 return authenticateSurfaceTextureLocked(bufferProducer);
636}
637
638bool SurfaceFlinger::authenticateSurfaceTextureLocked(
639 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800640 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700641 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800642}
643
Brian Anderson069b3652016-07-22 10:32:47 -0700644status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700645 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700646 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700647 FrameEvent::REQUESTED_PRESENT,
648 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700649 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700650 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700651 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700652 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700653 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700654 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700655 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700656 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700657 };
658 return NO_ERROR;
659}
660
Dan Stoza7f7da322014-05-02 15:26:25 -0700661status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
662 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700663 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700664 return BAD_VALUE;
665 }
666
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500667 if (!display.get())
668 return NAME_NOT_FOUND;
669
Jesse Hall692c7232012-11-08 15:41:56 -0800670 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700671 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800672 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700673 type = i;
674 break;
675 }
676 }
677
678 if (type < 0) {
679 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700680 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700681
Mathias Agopian8b736f12012-08-13 17:54:26 -0700682 // TODO: Not sure if display density should handled by SF any longer
683 class Density {
684 static int getDensityFromProperty(char const* propName) {
685 char property[PROPERTY_VALUE_MAX];
686 int density = 0;
687 if (property_get(propName, property, NULL) > 0) {
688 density = atoi(property);
689 }
690 return density;
691 }
692 public:
693 static int getEmuDensity() {
694 return getDensityFromProperty("qemu.sf.lcd_density"); }
695 static int getBuildDensity() {
696 return getDensityFromProperty("ro.sf.lcd_density"); }
697 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700698
Dan Stoza7f7da322014-05-02 15:26:25 -0700699 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700700
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700702 DisplayInfo info = DisplayInfo();
703
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 float xdpi = hwConfig->getDpiX();
705 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700706
707 if (type == DisplayDevice::DISPLAY_PRIMARY) {
708 // The density of the device is provided by a build property
709 float density = Density::getBuildDensity() / 160.0f;
710 if (density == 0) {
711 // the build doesn't provide a density -- this is wrong!
712 // use xdpi instead
713 ALOGE("ro.sf.lcd_density must be defined as a build property");
714 density = xdpi / 160.0f;
715 }
716 if (Density::getEmuDensity()) {
717 // if "qemu.sf.lcd_density" is specified, it overrides everything
718 xdpi = ydpi = density = Density::getEmuDensity();
719 density /= 160.0f;
720 }
721 info.density = density;
722
723 // TODO: this needs to go away (currently needed only by webkit)
724 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
725 info.orientation = hw->getOrientation();
726 } else {
727 // TODO: where should this value come from?
728 static const int TV_DENSITY = 213;
729 info.density = TV_DENSITY / 160.0f;
730 info.orientation = 0;
731 }
732
Dan Stoza9e56aa02015-11-02 13:00:03 -0800733 info.w = hwConfig->getWidth();
734 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 info.xdpi = xdpi;
736 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900738 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739
Andy McFadden91b2ca82014-06-13 14:04:23 -0700740 // This is how far in advance a buffer must be queued for
741 // presentation at a given time. If you want a buffer to appear
742 // on the screen at time N, you must submit the buffer before
743 // (N - presentationDeadline).
744 //
745 // Normally it's one full refresh period (to give SF a chance to
746 // latch the buffer), but this can be reduced by configuring a
747 // DispSync offset. Any additional delays introduced by the hardware
748 // composer or panel must be accounted for here.
749 //
750 // We add an additional 1ms to allow for processing time and
751 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 info.presentationDeadline = hwConfig->getVsyncPeriod() -
753 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700754
755 // All non-virtual displays are currently considered secure.
756 info.secure = true;
757
Michael Wright28f24d02016-07-12 13:30:53 -0700758 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 }
760
Dan Stoza7f7da322014-05-02 15:26:25 -0700761 return NO_ERROR;
762}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700763
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800764status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700765 DisplayStatInfo* stats) {
766 if (stats == NULL) {
767 return BAD_VALUE;
768 }
769
770 // FIXME for now we always return stats for the primary display
771 memset(stats, 0, sizeof(*stats));
772 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
773 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
774 return NO_ERROR;
775}
776
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700777int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800778 if (display == NULL) {
779 ALOGE("%s : display is NULL", __func__);
780 return BAD_VALUE;
781 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700782 sp<DisplayDevice> device(getDisplayDevice(display));
783 if (device != NULL) {
784 return device->getActiveConfig();
785 }
786 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700787}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700788
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700789void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
790 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
791 this);
792 int32_t type = hw->getDisplayType();
793 int currentMode = hw->getActiveConfig();
794
795 if (mode == currentMode) {
796 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
797 return;
798 }
799
800 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
801 ALOGW("Trying to set config for virtual display");
802 return;
803 }
804
805 hw->setActiveConfig(mode);
806 getHwComposer().setActiveConfig(type, mode);
807}
808
809status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
810 class MessageSetActiveConfig: public MessageBase {
811 SurfaceFlinger& mFlinger;
812 sp<IBinder> mDisplay;
813 int mMode;
814 public:
815 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
816 int mode) :
817 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
818 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700819 Vector<DisplayInfo> configs;
820 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700821 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700822 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700823 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700824 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700825 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700826 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
827 if (hw == NULL) {
828 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700829 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700830 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
831 ALOGW("Attempt to set active config = %d for virtual display",
832 mMode);
833 } else {
834 mFlinger.setActiveConfigInternal(hw, mMode);
835 }
836 return true;
837 }
838 };
839 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
840 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700841 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700842}
Michael Wright28f24d02016-07-12 13:30:53 -0700843status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
844 Vector<android_color_mode_t>* outColorModes) {
845 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
846 return BAD_VALUE;
847 }
848
849 if (!display.get()) {
850 return NAME_NOT_FOUND;
851 }
852
853 int32_t type = NAME_NOT_FOUND;
854 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
855 if (display == mBuiltinDisplays[i]) {
856 type = i;
857 break;
858 }
859 }
860
861 if (type < 0) {
862 return type;
863 }
864
865 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
866 outColorModes->clear();
867 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
868
869 return NO_ERROR;
870}
871
872android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
873 sp<DisplayDevice> device(getDisplayDevice(display));
874 if (device != nullptr) {
875 return device->getActiveColorMode();
876 }
877 return static_cast<android_color_mode_t>(BAD_VALUE);
878}
879
880void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
881 android_color_mode_t mode) {
882 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
883 this);
884 int32_t type = hw->getDisplayType();
885 android_color_mode_t currentMode = hw->getActiveColorMode();
886
887 if (mode == currentMode) {
888 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
889 return;
890 }
891
892 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
893 ALOGW("Trying to set config for virtual display");
894 return;
895 }
896
897 hw->setActiveColorMode(mode);
898 getHwComposer().setActiveColorMode(type, mode);
899}
900
901
902status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
903 android_color_mode_t colorMode) {
904 class MessageSetActiveColorMode: public MessageBase {
905 SurfaceFlinger& mFlinger;
906 sp<IBinder> mDisplay;
907 android_color_mode_t mMode;
908 public:
909 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
910 android_color_mode_t mode) :
911 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
912 virtual bool handler() {
913 Vector<android_color_mode_t> modes;
914 mFlinger.getDisplayColorModes(mDisplay, &modes);
915 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
916 if (mMode < 0 || !exists) {
917 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
918 mDisplay.get());
919 return true;
920 }
921 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
922 if (hw == nullptr) {
923 ALOGE("Attempt to set active color mode = %d for null display %p",
924 mMode, mDisplay.get());
925 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
926 ALOGW("Attempt to set active color mode= %d for virtual display",
927 mMode);
928 } else {
929 mFlinger.setActiveColorModeInternal(hw, mMode);
930 }
931 return true;
932 }
933 };
934 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
935 postMessageSync(msg);
936 return NO_ERROR;
937}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700938
Svetoslavd85084b2014-03-20 10:28:31 -0700939status_t SurfaceFlinger::clearAnimationFrameStats() {
940 Mutex::Autolock _l(mStateLock);
941 mAnimFrameTracker.clearStats();
942 return NO_ERROR;
943}
944
945status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
946 Mutex::Autolock _l(mStateLock);
947 mAnimFrameTracker.getStats(outStats);
948 return NO_ERROR;
949}
950
Dan Stozac4f471e2016-03-24 09:31:08 -0700951status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
952 HdrCapabilities* outCapabilities) const {
953 Mutex::Autolock _l(mStateLock);
954
955 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
956 if (displayDevice == nullptr) {
957 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
958 return BAD_VALUE;
959 }
960
961 std::unique_ptr<HdrCapabilities> capabilities =
962 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
963 if (capabilities) {
964 std::swap(*outCapabilities, *capabilities);
965 } else {
966 return BAD_VALUE;
967 }
968
969 return NO_ERROR;
970}
971
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700972status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
973 if (enable == mInjectVSyncs) {
974 return NO_ERROR;
975 }
976
977 if (enable) {
978 mInjectVSyncs = enable;
979 ALOGV("VSync Injections enabled");
980 if (mVSyncInjector.get() == nullptr) {
981 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700982 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700983 }
984 mEventQueue.setEventThread(mInjectorEventThread);
985 } else {
986 mInjectVSyncs = enable;
987 ALOGV("VSync Injections disabled");
988 mEventQueue.setEventThread(mSFEventThread);
989 mVSyncInjector.clear();
990 }
991 return NO_ERROR;
992}
993
994status_t SurfaceFlinger::injectVSync(nsecs_t when) {
995 if (!mInjectVSyncs) {
996 ALOGE("VSync Injections not enabled");
997 return BAD_VALUE;
998 }
999 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1000 ALOGV("Injecting VSync inside SurfaceFlinger");
1001 mVSyncInjector->onInjectSyncEvent(when);
1002 }
1003 return NO_ERROR;
1004}
1005
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001006// ----------------------------------------------------------------------------
1007
1008sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001009 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001010}
1011
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001012// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001013
1014void SurfaceFlinger::waitForEvent() {
1015 mEventQueue.waitMessage();
1016}
1017
1018void SurfaceFlinger::signalTransaction() {
1019 mEventQueue.invalidate();
1020}
1021
1022void SurfaceFlinger::signalLayerUpdate() {
1023 mEventQueue.invalidate();
1024}
1025
1026void SurfaceFlinger::signalRefresh() {
1027 mEventQueue.refresh();
1028}
1029
1030status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001031 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001032 return mEventQueue.postMessage(msg, reltime);
1033}
1034
1035status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001036 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001037 status_t res = mEventQueue.postMessage(msg, reltime);
1038 if (res == NO_ERROR) {
1039 msg->wait();
1040 }
1041 return res;
1042}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001043
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001044void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001045 do {
1046 waitForEvent();
1047 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001048}
1049
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001050void SurfaceFlinger::enableHardwareVsync() {
1051 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001052 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001053 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001054 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1055 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001056 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001057 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001058}
1059
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061 Mutex::Autolock _l(mHWVsyncLock);
1062
Jesse Hall948fe0c2013-10-14 12:56:09 -07001063 if (makeAvailable) {
1064 mHWVsyncAvailable = true;
1065 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001066 // Hardware vsync is not currently available, so abort the resync
1067 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001068 return;
1069 }
1070
Dan Stoza9e56aa02015-11-02 13:00:03 -08001071 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1072 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073
1074 mPrimaryDispSync.reset();
1075 mPrimaryDispSync.setPeriod(period);
1076
1077 if (!mPrimaryHWVsyncEnabled) {
1078 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001079 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1080 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001081 mPrimaryHWVsyncEnabled = true;
1082 }
1083}
1084
Jesse Hall948fe0c2013-10-14 12:56:09 -07001085void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001086 Mutex::Autolock _l(mHWVsyncLock);
1087 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001088 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1089 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090 mPrimaryDispSync.endResync();
1091 mPrimaryHWVsyncEnabled = false;
1092 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001093 if (makeUnavailable) {
1094 mHWVsyncAvailable = false;
1095 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001096}
1097
Tim Murray4a4e4a22016-04-19 16:29:23 +00001098void SurfaceFlinger::resyncWithRateLimit() {
1099 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1100 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001101 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001102 }
1103}
1104
Steven Thomas3cfac282017-02-06 12:29:30 -08001105void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1106 nsecs_t timestamp) {
1107 Mutex::Autolock lock(mStateLock);
1108 // Ignore any vsyncs from the non-active hardware composer.
1109 if (composer != mHwc) {
1110 return;
1111 }
1112
Jamie Gennisd1700752013-10-14 12:22:52 -07001113 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 { // Scope for the lock
1116 Mutex::Autolock _l(mHWVsyncLock);
1117 if (type == 0 && mPrimaryHWVsyncEnabled) {
1118 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001120 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001121
1122 if (needsHwVsync) {
1123 enableHardwareVsync();
1124 } else {
1125 disableHardwareVsync(false);
1126 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001127}
1128
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001129void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1130 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1131 *compositorTiming = mCompositorTiming;
1132}
1133
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1135 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1136 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1137 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001138
Dan Stoza9e56aa02015-11-02 13:00:03 -08001139 // All non-virtual displays are currently considered secure.
1140 bool isSecure = true;
1141
1142 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001143
1144 // When we're using the vr composer, the assumption is that we've
1145 // already created the IBinder object for the primary display.
1146 if (!mHwc->isUsingVrComposer()) {
1147 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1148 }
1149
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 wp<IBinder> token = mBuiltinDisplays[type];
1151
1152 sp<IGraphicBufferProducer> producer;
1153 sp<IGraphicBufferConsumer> consumer;
1154 BufferQueue::createBufferQueue(&producer, &consumer,
1155 new GraphicBufferAlloc());
1156
1157 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1158 DisplayDevice::DISPLAY_PRIMARY, consumer);
1159 sp<DisplayDevice> hw = new DisplayDevice(this,
1160 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1161 producer, mRenderEngine->getEGLConfig());
1162 mDisplays.add(token, hw);
1163 } else {
1164 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001165 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001166 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001167 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001168 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001169 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1170 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001171 }
1172 setTransactionFlags(eDisplayTransactionNeeded);
1173
Andy McFadden9e9689c2012-10-10 18:17:51 -07001174 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001175 }
Mathias Agopian86303202012-07-24 22:46:10 -07001176}
1177
Steven Thomas3cfac282017-02-06 12:29:30 -08001178void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1179 Mutex::Autolock lock(mStateLock);
1180 if (composer == mHwc) {
1181 repaintEverything();
1182 } else {
1183 // This isn't from our current hardware composer. If it's a callback
1184 // from the real composer, forward the refresh request to vr
1185 // flinger. Otherwise ignore it.
1186 if (!composer->isUsingVrComposer()) {
1187 mVrFlinger->OnHardwareComposerRefresh();
1188 }
1189 }
1190}
1191
Dan Stoza9e56aa02015-11-02 13:00:03 -08001192void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001193 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 getHwComposer().setVsyncEnabled(disp,
1195 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001196}
1197
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001198void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1199 for (size_t i = 0; i < layers.size(); ++i) {
1200 layers[i]->clearHwcLayers();
1201 }
1202}
1203
1204void SurfaceFlinger::resetHwc() {
1205 disableHardwareVsync(true);
1206 clearHwcLayers(mDrawingState.layersSortedByZ);
1207 clearHwcLayers(mCurrentState.layersSortedByZ);
1208 // Clear the drawing state so that the logic inside of
1209 // handleTransactionLocked will fire. It will determine the delta between
1210 // mCurrentState and mDrawingState and re-apply all changes when we make the
1211 // transition.
1212 mDrawingState.displays.clear();
1213 mDisplays.clear();
1214}
1215
1216void SurfaceFlinger::updateVrMode() {
Mark Urbanus209beca2017-02-23 11:16:04 -08001217 bool enteringVrMode = mEnterVrMode;
1218 if (enteringVrMode == mHwc->isUsingVrComposer()) {
1219 return;
1220 }
1221 if (enteringVrMode && !mVrHwc) {
1222 // Construct new HWComposer without holding any locks.
1223 mVrHwc = new HWComposer(true);
1224 ALOGV("Vr HWC created");
1225 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001226 {
1227 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001228
1229 if (enteringVrMode) {
1230 // Start vrflinger thread, if it hasn't been started already.
1231 if (!mVrFlinger) {
1232 mVrFlinger = std::make_unique<dvr::VrFlinger>();
1233 int err = mVrFlinger->Run(mHwc->getComposer());
1234 if (err != NO_ERROR) {
1235 ALOGE("Failed to run vrflinger: %s (%d)", strerror(-err), err);
1236 mVrFlinger.reset();
1237 mEnterVrMode = false;
1238 return;
1239 }
1240 }
1241
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001242 resetHwc();
1243
1244 mHwc = mVrHwc;
1245 mVrFlinger->EnterVrMode();
1246 } else {
1247 mVrFlinger->ExitVrMode();
1248
1249 resetHwc();
1250
1251 mHwc = mRealHwc;
1252 enableHardwareVsync();
1253 }
1254
1255 mVisibleRegionsDirty = true;
1256 invalidateHwcGeometry();
1257 android_atomic_or(1, &mRepaintEverything);
1258 setTransactionFlags(eDisplayTransactionNeeded);
1259 }
1260 if (mVrHwc) {
1261 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
1262 }
1263}
1264
Mathias Agopian4fec8732012-06-29 14:12:52 -07001265void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001266 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001268 case MessageQueue::INVALIDATE: {
Mark Urbanus3a8f7942017-03-02 15:44:10 -08001269 // TODO(eieio): Tied to a conditional until SELinux issues
1270 // are resolved.
1271 if (mVrModeSupported) {
1272 updateVrMode();
1273 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001274
Dan Stoza50182882016-07-08 12:02:20 -07001275 bool frameMissed = !mHadClientComposition &&
1276 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001277 (mPreviousPresentFence->getSignalTime() ==
1278 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001279 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001280 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001281 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001282 signalLayerUpdate();
1283 break;
1284 }
1285
Dan Stoza6b9454d2014-11-07 16:00:59 -08001286 bool refreshNeeded = handleMessageTransaction();
1287 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001288 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001289 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001290 // Signal a refresh if a transaction modified the window state,
1291 // a new buffer was latched, or if HWC has requested a full
1292 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001293 signalRefresh();
1294 }
1295 break;
1296 }
1297 case MessageQueue::REFRESH: {
1298 handleMessageRefresh();
1299 break;
1300 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001301 }
1302}
1303
Dan Stoza6b9454d2014-11-07 16:00:59 -08001304bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001305 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001306 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001307 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001308 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001309 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001310 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001311}
1312
Dan Stoza6b9454d2014-11-07 16:00:59 -08001313bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001314 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001315 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001316}
1317
1318void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001319 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001320
Pablo Ceballos40845df2016-01-25 17:41:15 -08001321 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001322
Brian Andersond6927fb2016-07-23 23:37:30 -07001323 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001324 rebuildLayerStacks();
1325 setUpHWComposer();
1326 doDebugFlashRegions();
1327 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001328 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001329
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001330 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001331
1332 mHadClientComposition = false;
1333 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1334 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1335 mHadClientComposition = mHadClientComposition ||
1336 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1337 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001338
Dan Stoza9e56aa02015-11-02 13:00:03 -08001339 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001340}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001341
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342void SurfaceFlinger::doDebugFlashRegions()
1343{
1344 // is debugging enabled
1345 if (CC_LIKELY(!mDebugRegion))
1346 return;
1347
1348 const bool repaintEverything = mRepaintEverything;
1349 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1350 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001351 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001352 // transform the dirty region into this screen's coordinate space
1353 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1354 if (!dirtyRegion.isEmpty()) {
1355 // redraw the whole screen
1356 doComposeSurfaces(hw, Region(hw->bounds()));
1357
1358 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001359 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001360 RenderEngine& engine(getRenderEngine());
1361 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1362
Mathias Agopianda27af92012-09-13 18:17:13 -07001363 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001364 }
1365 }
1366 }
1367
1368 postFramebuffer();
1369
1370 if (mDebugRegion > 1) {
1371 usleep(mDebugRegion * 1000);
1372 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001373
Dan Stoza9e56aa02015-11-02 13:00:03 -08001374 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001375 auto& displayDevice = mDisplays[displayId];
1376 if (!displayDevice->isDisplayOn()) {
1377 continue;
1378 }
1379
1380 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001381 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1382 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001383 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001384}
1385
Brian Andersond6927fb2016-07-23 23:37:30 -07001386void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001387{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001388 ATRACE_CALL();
1389 ALOGV("preComposition");
1390
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001392 mDrawingState.traverseInZOrder([&](Layer* layer) {
1393 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001394 needExtraInvalidate = true;
1395 }
Robert Carr2047fae2016-11-28 14:09:09 -08001396 });
1397
Mathias Agopiancd60f992012-08-16 16:28:27 -07001398 if (needExtraInvalidate) {
1399 signalLayerUpdate();
1400 }
1401}
1402
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001403void SurfaceFlinger::updateCompositorTiming(
1404 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1405 std::shared_ptr<FenceTime>& presentFenceTime) {
1406 // Update queue of past composite+present times and determine the
1407 // most recently known composite to present latency.
1408 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1409 nsecs_t compositeToPresentLatency = -1;
1410 while (!mCompositePresentTimes.empty()) {
1411 CompositePresentTime& cpt = mCompositePresentTimes.front();
1412 // Cached values should have been updated before calling this method,
1413 // which helps avoid duplicate syscalls.
1414 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1415 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1416 break;
1417 }
1418 compositeToPresentLatency = displayTime - cpt.composite;
1419 mCompositePresentTimes.pop();
1420 }
1421
1422 // Don't let mCompositePresentTimes grow unbounded, just in case.
1423 while (mCompositePresentTimes.size() > 16) {
1424 mCompositePresentTimes.pop();
1425 }
1426
1427 // Integer division and modulo round toward 0 not -inf, so we need to
1428 // treat negative and positive offsets differently.
1429 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1430 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1431 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1432
1433 // Snap the latency to a value that removes scheduling jitter from the
1434 // composition and present times, which often have >1ms of jitter.
1435 // Reducing jitter is important if an app attempts to extrapolate
1436 // something (such as user input) to an accurate diasplay time.
1437 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1438 // with (presentLatency % interval).
1439 nsecs_t snappedCompositeToPresentLatency = -1;
1440 if (compositeToPresentLatency >= 0) {
1441 nsecs_t bias = vsyncInterval / 2;
1442 int64_t extraVsyncs =
1443 (compositeToPresentLatency - idealLatency + bias) /
1444 vsyncInterval;
1445 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1446 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1447 }
1448
1449 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1450 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1451 mCompositorTiming.interval = vsyncInterval;
1452 if (snappedCompositeToPresentLatency >= 0) {
1453 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1454 }
1455}
1456
1457void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 ATRACE_CALL();
1460 ALOGV("postComposition");
1461
Brian Anderson3546a3f2016-07-14 11:51:14 -07001462 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001463 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001464 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001465 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001466 }
1467
Brian Andersond6927fb2016-07-23 23:37:30 -07001468 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001469
1470 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1471 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1472 glCompositionDoneFenceTime =
1473 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1474 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1475 } else {
1476 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1477 }
1478 mGlCompositionDoneTimeline.updateSignalTimes();
1479
1480 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1481 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1482 mDisplayTimeline.push(displayFenceTime);
1483 mDisplayTimeline.updateSignalTimes();
1484
1485 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1486 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1487 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1488 presentFenceTime = &displayFenceTime;
1489 } else {
1490 retireFenceTime = &displayFenceTime;
1491 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001492
1493 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1494 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1495
1496 // We use the refreshStartTime which might be sampled a little later than
1497 // when we started doing work for this frame, but that should be okay
1498 // since updateCompositorTiming has snapping logic.
1499 updateCompositorTiming(
1500 vsyncPhase, vsyncInterval, refreshStartTime, displayFenceTime);
1501
Robert Carr2047fae2016-11-28 14:09:09 -08001502 mDrawingState.traverseInZOrder([&](Layer* layer) {
1503 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504 *presentFenceTime, *retireFenceTime, mCompositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001505 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001506 recordBufferingStats(layer->getName().string(),
1507 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001508 }
Robert Carr2047fae2016-11-28 14:09:09 -08001509 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001510
Brian Anderson3d4039d2016-09-23 16:31:30 -07001511 if (displayFence->isValid()) {
1512 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001513 enableHardwareVsync();
1514 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001515 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001516 }
1517 }
1518
Andy McFadden5167ec62014-05-22 13:08:43 -07001519 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001520 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001521 enableHardwareVsync();
1522 }
1523 }
1524
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001525 if (mAnimCompositionPending) {
1526 mAnimCompositionPending = false;
1527
Brian Anderson3d4039d2016-09-23 16:31:30 -07001528 if (displayFenceTime->isValid()) {
1529 mAnimFrameTracker.setActualPresentFence(
1530 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001531 } else {
1532 // The HWC doesn't support present fences, so use the refresh
1533 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001534 nsecs_t presentTime =
1535 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001536 mAnimFrameTracker.setActualPresentTime(presentTime);
1537 }
1538 mAnimFrameTracker.advanceFrame();
1539 }
Dan Stozab90cf072015-03-05 11:05:59 -08001540
1541 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1542 return;
1543 }
1544
1545 nsecs_t currentTime = systemTime();
1546 if (mHasPoweredOff) {
1547 mHasPoweredOff = false;
1548 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001549 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001550 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001551 if (numPeriods < NUM_BUCKETS - 1) {
1552 mFrameBuckets[numPeriods] += elapsedTime;
1553 } else {
1554 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1555 }
1556 mTotalTime += elapsedTime;
1557 }
1558 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001559}
1560
1561void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001562 ATRACE_CALL();
1563 ALOGV("rebuildLayerStacks");
1564
Mathias Agopiancd60f992012-08-16 16:28:27 -07001565 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001566 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1567 ATRACE_CALL();
1568 mVisibleRegionsDirty = false;
1569 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001570
Jeff Sharkey76488112017-02-27 14:15:18 -07001571 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1572 Region opaqueRegion;
1573 Region dirtyRegion;
1574 Vector<sp<Layer>> layersSortedByZ;
1575 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1576 const Transform& tr(displayDevice->getTransform());
1577 const Rect bounds(displayDevice->getBounds());
1578 if (displayDevice->isDisplayOn()) {
1579 computeVisibleRegions(
1580 displayDevice->getLayerStack(), dirtyRegion,
1581 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001582
Jeff Sharkey76488112017-02-27 14:15:18 -07001583 mDrawingState.traverseInZOrder([&](Layer* layer) {
1584 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1585 Region drawRegion(tr.transform(
1586 layer->visibleNonTransparentRegion));
1587 drawRegion.andSelf(bounds);
1588 if (!drawRegion.isEmpty()) {
1589 layersSortedByZ.add(layer);
1590 } else {
1591 // Clear out the HWC layer if this layer was
1592 // previously visible, but no longer is
1593 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1594 nullptr);
1595 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001596 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001597 // WM changes displayDevice->layerStack upon sleep/awake.
1598 // Here we make sure we delete the HWC layers even if
1599 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001600 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1601 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001602 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001603 });
1604 }
1605 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1606 displayDevice->undefinedRegion.set(bounds);
1607 displayDevice->undefinedRegion.subtractSelf(
1608 tr.transform(opaqueRegion));
1609 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001610 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001611 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001612}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001613
Mathias Agopiancd60f992012-08-16 16:28:27 -07001614void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001615 ATRACE_CALL();
1616 ALOGV("setUpHWComposer");
1617
Jesse Hall028dc8f2013-08-20 16:35:32 -07001618 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001619 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1620 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1621 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1622
1623 // If nothing has changed (!dirty), don't recompose.
1624 // If something changed, but we don't currently have any visible layers,
1625 // and didn't when we last did a composition, then skip it this time.
1626 // The second rule does two things:
1627 // - When all layers are removed from a display, we'll emit one black
1628 // frame, then nothing more until we get new layers.
1629 // - When a display is created with a private layer stack, we won't
1630 // emit any black frames until a layer is added to the layer stack.
1631 bool mustRecompose = dirty && !(empty && wasEmpty);
1632
1633 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1634 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1635 mustRecompose ? "doing" : "skipping",
1636 dirty ? "+" : "-",
1637 empty ? "+" : "-",
1638 wasEmpty ? "+" : "-");
1639
Dan Stoza71433162014-02-04 16:22:36 -08001640 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001641
1642 if (mustRecompose) {
1643 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1644 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001645 }
1646
Dan Stoza9e56aa02015-11-02 13:00:03 -08001647 // build the h/w work list
1648 if (CC_UNLIKELY(mGeometryInvalid)) {
1649 mGeometryInvalid = false;
1650 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1651 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1652 const auto hwcId = displayDevice->getHwcDisplayId();
1653 if (hwcId >= 0) {
1654 const Vector<sp<Layer>>& currentLayers(
1655 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001656 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001657 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 if (!layer->hasHwcLayer(hwcId)) {
1659 auto hwcLayer = mHwc->createLayer(hwcId);
1660 if (hwcLayer) {
1661 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1662 } else {
1663 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001665 }
1666 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001667
Robert Carrae060832016-11-28 10:51:00 -08001668 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001669 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001670 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001671 }
1672 }
1673 }
1674 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001675 }
Riley Andrews03414a12014-07-01 14:22:59 -07001676
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001677
1678 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1679
Dan Stoza9e56aa02015-11-02 13:00:03 -08001680 // Set the per-frame data
1681 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1682 auto& displayDevice = mDisplays[displayId];
1683 const auto hwcId = displayDevice->getHwcDisplayId();
1684 if (hwcId < 0) {
1685 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001686 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001687 if (colorMatrix != mPreviousColorMatrix) {
1688 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1689 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1690 "display %zd: %d", displayId, result);
1691 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1693 layer->setPerFrameData(displayDevice);
1694 }
1695 }
1696
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001697 mPreviousColorMatrix = colorMatrix;
1698
Dan Stoza9e56aa02015-11-02 13:00:03 -08001699 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001700 auto& displayDevice = mDisplays[displayId];
1701 if (!displayDevice->isDisplayOn()) {
1702 continue;
1703 }
1704
1705 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001706 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1707 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001708 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001709}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001710
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711void SurfaceFlinger::doComposition() {
1712 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001713 ALOGV("doComposition");
1714
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001715 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001716 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001717 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001718 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719 // transform the dirty region into this screen's coordinate space
1720 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001721
1722 // repaint the framebuffer (if needed)
1723 doDisplayComposition(hw, dirtyRegion);
1724
Mathias Agopiancd60f992012-08-16 16:28:27 -07001725 hw->dirtyRegion.clear();
1726 hw->flip(hw->swapRegion);
1727 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001728 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001730 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001731}
1732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001733void SurfaceFlinger::postFramebuffer()
1734{
Mathias Agopian841cde52012-03-01 15:44:37 -08001735 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001736 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001737
Mathias Agopiana44b0412011-10-16 18:46:35 -07001738 const nsecs_t now = systemTime();
1739 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001740
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1742 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001743 if (!displayDevice->isDisplayOn()) {
1744 continue;
1745 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001746 const auto hwcId = displayDevice->getHwcDisplayId();
1747 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001748 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001749 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001750 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001751 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1753 sp<Fence> releaseFence = Fence::NO_FENCE;
1754 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1755 releaseFence = displayDevice->getClientTargetAcquireFence();
1756 } else {
1757 auto hwcLayer = layer->getHwcLayer(hwcId);
1758 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001759 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 layer->onLayerDisplayed(releaseFence);
1761 }
1762 if (hwcId >= 0) {
1763 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001764 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001765 }
1766
Mathias Agopiana44b0412011-10-16 18:46:35 -07001767 mLastSwapBufferTime = systemTime() - now;
1768 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001769
1770 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1771 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1772 logFrameStats();
1773 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001774}
1775
Mathias Agopian87baae12012-07-31 12:38:26 -07001776void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777{
Mathias Agopian841cde52012-03-01 15:44:37 -08001778 ATRACE_CALL();
1779
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001780 // here we keep a copy of the drawing state (that is the state that's
1781 // going to be overwritten by handleTransactionLocked()) outside of
1782 // mStateLock so that the side-effects of the State assignment
1783 // don't happen with mStateLock held (which can cause deadlocks).
1784 State drawingState(mDrawingState);
1785
Mathias Agopianca4d3602011-05-19 15:38:14 -07001786 Mutex::Autolock _l(mStateLock);
1787 const nsecs_t now = systemTime();
1788 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001789
Mathias Agopianca4d3602011-05-19 15:38:14 -07001790 // Here we're guaranteed that some transaction flags are set
1791 // so we can call handleTransactionLocked() unconditionally.
1792 // We call getTransactionFlags(), which will also clear the flags,
1793 // with mStateLock held to guarantee that mCurrentState won't change
1794 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001795
Mathias Agopiane57f2922012-08-09 16:29:12 -07001796 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001797 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001798
Mathias Agopianca4d3602011-05-19 15:38:14 -07001799 mLastTransactionTime = systemTime() - now;
1800 mDebugInTransaction = 0;
1801 invalidateHwcGeometry();
1802 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001803}
1804
Mathias Agopian87baae12012-07-31 12:38:26 -07001805void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001806{
Dan Stoza7dde5992015-05-22 09:51:44 -07001807 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001808 mCurrentState.traverseInZOrder([](Layer* layer) {
1809 layer->notifyAvailableFrames();
1810 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001811
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812 /*
1813 * Traversal of the children
1814 * (perform the transaction for each of them if needed)
1815 */
1816
Mathias Agopian3559b072012-08-15 13:46:03 -07001817 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001818 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001820 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821
1822 const uint32_t flags = layer->doTransaction(0);
1823 if (flags & Layer::eVisibleRegion)
1824 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001825 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001826 }
1827
1828 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001829 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001830 */
1831
Mathias Agopiane57f2922012-08-09 16:29:12 -07001832 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001833 // here we take advantage of Vector's copy-on-write semantics to
1834 // improve performance by skipping the transaction entirely when
1835 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001836 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1837 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001838 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001839 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001840 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001841 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001842
1843 // find the displays that were removed
1844 // (ie: in drawing state but not in current state)
1845 // also handle displays that changed
1846 // (ie: displays that are in both lists)
1847 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001848 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1849 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001850 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001851 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001852 // Call makeCurrent() on the primary display so we can
1853 // be sure that nothing associated with this display
1854 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001855 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001856 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001857 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1858 if (hw != NULL)
1859 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001860 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001861 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001862 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001863 } else {
1864 ALOGW("trying to remove the main display");
1865 }
1866 } else {
1867 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001868 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001869 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001870 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1871 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001872 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001873 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001874 // recreating the DisplayDevice, so we just remove it
1875 // from the drawing state, so that it get re-added
1876 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001877 sp<DisplayDevice> hw(getDisplayDevice(display));
1878 if (hw != NULL)
1879 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001880 mDisplays.removeItem(display);
1881 mDrawingState.displays.removeItemsAt(i);
1882 dc--; i--;
1883 // at this point we must loop to the next item
1884 continue;
1885 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001886
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001887 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001888 if (disp != NULL) {
1889 if (state.layerStack != draw[i].layerStack) {
1890 disp->setLayerStack(state.layerStack);
1891 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001892 if ((state.orientation != draw[i].orientation)
1893 || (state.viewport != draw[i].viewport)
1894 || (state.frame != draw[i].frame))
1895 {
1896 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001897 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001898 }
Michael Lentine47e45402014-07-18 15:34:25 -07001899 if (state.width != draw[i].width || state.height != draw[i].height) {
1900 disp->setDisplaySize(state.width, state.height);
1901 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001902 }
1903 }
1904 }
1905
1906 // find displays that were added
1907 // (ie: in current state but not in drawing state)
1908 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001909 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001910 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001911
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001912 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001913 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001914 sp<IGraphicBufferProducer> bqProducer;
1915 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001916 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1917 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001918
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001920 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001921 // Virtual displays without a surface are dormant:
1922 // they have external state (layer stack, projection,
1923 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001924 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001925
Dan Stoza8cf150a2016-08-02 10:27:31 -07001926 if (mUseHwcVirtualDisplays) {
1927 int width = 0;
1928 int status = state.surface->query(
1929 NATIVE_WINDOW_WIDTH, &width);
1930 ALOGE_IF(status != NO_ERROR,
1931 "Unable to query width (%d)", status);
1932 int height = 0;
1933 status = state.surface->query(
1934 NATIVE_WINDOW_HEIGHT, &height);
1935 ALOGE_IF(status != NO_ERROR,
1936 "Unable to query height (%d)", status);
1937 int intFormat = 0;
1938 status = state.surface->query(
1939 NATIVE_WINDOW_FORMAT, &intFormat);
1940 ALOGE_IF(status != NO_ERROR,
1941 "Unable to query format (%d)", status);
1942 auto format = static_cast<android_pixel_format_t>(
1943 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001944
Dan Stoza8cf150a2016-08-02 10:27:31 -07001945 mHwc->allocateVirtualDisplay(width, height, &format,
1946 &hwcId);
1947 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948
Dan Stoza5cf424b2016-05-20 14:02:39 -07001949 // TODO: Plumb requested format back up to consumer
1950
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 sp<VirtualDisplaySurface> vds =
1952 new VirtualDisplaySurface(*mHwc,
1953 hwcId, state.surface, bqProducer,
1954 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001955
1956 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001957 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001958 }
1959 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001960 ALOGE_IF(state.surface!=NULL,
1961 "adding a supported display, but rendering "
1962 "surface is provided (%p), ignoring it",
1963 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001964
1965 hwcId = state.type;
1966 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
1967 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07001968 }
1969
1970 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001971 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001972 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 state.type, hwcId, state.isSecure, display,
1974 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001975 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001976 hw->setLayerStack(state.layerStack);
1977 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001978 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001979 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001980 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001982 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001983 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001984 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001985 }
1986 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001987 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001988 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989
Mathias Agopian84300952012-11-21 16:02:13 -08001990 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1991 // The transform hint might have changed for some layers
1992 // (either because a display has changed, or because a layer
1993 // as changed).
1994 //
1995 // Walk through all the layers in currentLayers,
1996 // and update their transform hint.
1997 //
1998 // If a layer is visible only on a single display, then that
1999 // display is used to calculate the hint, otherwise we use the
2000 // default display.
2001 //
2002 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2003 // the hint is set before we acquire a buffer from the surface texture.
2004 //
2005 // NOTE: layer transactions have taken place already, so we use their
2006 // drawing state. However, SurfaceFlinger's own transaction has not
2007 // happened yet, so we must use the current state layer list
2008 // (soon to become the drawing state list).
2009 //
2010 sp<const DisplayDevice> disp;
2011 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002012 bool first = true;
2013 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002014 // NOTE: we rely on the fact that layers are sorted by
2015 // layerStack first (so we don't have to traverse the list
2016 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002017 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002018 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002019 currentlayerStack = layerStack;
2020 // figure out if this layerstack is mirrored
2021 // (more than one display) if so, pick the default display,
2022 // if not, pick the only display it's on.
2023 disp.clear();
2024 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2025 sp<const DisplayDevice> hw(mDisplays[dpy]);
2026 if (hw->getLayerStack() == currentlayerStack) {
2027 if (disp == NULL) {
2028 disp = hw;
2029 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002030 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002031 break;
2032 }
2033 }
2034 }
2035 }
Chet Haase91d25932013-04-11 15:24:55 -07002036 if (disp == NULL) {
2037 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2038 // redraw after transform hint changes. See bug 8508397.
2039
2040 // could be null when this layer is using a layerStack
2041 // that is not visible on any display. Also can occur at
2042 // screen off/on times.
2043 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08002044 }
Chet Haase91d25932013-04-11 15:24:55 -07002045 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002046
2047 first = false;
2048 });
Mathias Agopian84300952012-11-21 16:02:13 -08002049 }
2050
2051
Mathias Agopian3559b072012-08-15 13:46:03 -07002052 /*
2053 * Perform our own transaction if needed
2054 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002055
2056 if (mLayersAdded) {
2057 mLayersAdded = false;
2058 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002059 mVisibleRegionsDirty = true;
2060 }
2061
2062 // some layers might have been removed, so
2063 // we need to update the regions they're exposing.
2064 if (mLayersRemoved) {
2065 mLayersRemoved = false;
2066 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002067 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002068 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002069 // this layer is not visible anymore
2070 // TODO: we could traverse the tree from front to back and
2071 // compute the actual visible region
2072 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002073 Region visibleReg;
2074 visibleReg.set(layer->computeScreenBounds());
2075 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002076 }
Robert Carr2047fae2016-11-28 14:09:09 -08002077 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002078 }
2079
2080 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002081
2082 updateCursorAsync();
2083}
2084
2085void SurfaceFlinger::updateCursorAsync()
2086{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2088 auto& displayDevice = mDisplays[displayId];
2089 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002090 continue;
2091 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092
2093 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2094 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002095 }
2096 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002097}
2098
2099void SurfaceFlinger::commitTransaction()
2100{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002101 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002103 for (const auto& l : mLayersPendingRemoval) {
2104 recordBufferingStats(l->getName().string(),
2105 l->getOccupancyHistory(true));
2106 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002107 }
2108 mLayersPendingRemoval.clear();
2109 }
2110
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002111 // If this transaction is part of a window animation then the next frame
2112 // we composite should be considered an animation as well.
2113 mAnimCompositionPending = mAnimTransactionPending;
2114
Mathias Agopian4fec8732012-06-29 14:12:52 -07002115 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002116 mDrawingState.traverseInZOrder([](Layer* layer) {
2117 layer->commitChildList();
2118 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002119 mTransactionPending = false;
2120 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002121 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002122}
2123
Robert Carr2047fae2016-11-28 14:09:09 -08002124void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126{
Mathias Agopian841cde52012-03-01 15:44:37 -08002127 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130 Region aboveOpaqueLayers;
2131 Region aboveCoveredLayers;
2132 Region dirty;
2133
Mathias Agopian87baae12012-07-31 12:38:26 -07002134 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135
Robert Carr2047fae2016-11-28 14:09:09 -08002136 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002138 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139
Jesse Hall01e29052013-02-19 16:13:35 -08002140 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002141 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002142 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002143
Mathias Agopianab028732010-03-16 16:41:46 -07002144 /*
2145 * opaqueRegion: area of a surface that is fully opaque.
2146 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002147 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002148
2149 /*
2150 * visibleRegion: area of a surface that is visible on screen
2151 * and not fully transparent. This is essentially the layer's
2152 * footprint minus the opaque regions above it.
2153 * Areas covered by a translucent surface are considered visible.
2154 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002155 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002156
2157 /*
2158 * coveredRegion: area of a surface that is covered by all
2159 * visible regions above it (which includes the translucent areas).
2160 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002161 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002162
Jesse Halla8026d22012-09-25 13:25:04 -07002163 /*
2164 * transparentRegion: area of a surface that is hinted to be completely
2165 * transparent. This is only used to tell when the layer has no visible
2166 * non-transparent regions and can be removed from the layer list. It
2167 * does not affect the visibleRegion of this layer or any layers
2168 * beneath it. The hint may not be correct if apps don't respect the
2169 * SurfaceView restrictions (which, sadly, some don't).
2170 */
2171 Region transparentRegion;
2172
Mathias Agopianab028732010-03-16 16:41:46 -07002173
2174 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002175 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002176 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002179 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002180 if (!visibleRegion.isEmpty()) {
2181 // Remove the transparent area from the visible region
2182 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002183 if (tr.preserveRects()) {
2184 // transform the transparent region
2185 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002186 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002187 // transformation too complex, can't do the
2188 // transparent region optimization.
2189 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002190 }
Mathias Agopianab028732010-03-16 16:41:46 -07002191 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192
Mathias Agopianab028732010-03-16 16:41:46 -07002193 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002194 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002196 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2197 // the opaque region is the layer's footprint
2198 opaqueRegion = visibleRegion;
2199 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 }
2201 }
2202
Mathias Agopianab028732010-03-16 16:41:46 -07002203 // Clip the covered region to the visible region
2204 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2205
2206 // Update aboveCoveredLayers for next (lower) layer
2207 aboveCoveredLayers.orSelf(visibleRegion);
2208
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209 // subtract the opaque region covered by the layers above us
2210 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002211
2212 // compute this layer's dirty region
2213 if (layer->contentDirty) {
2214 // we need to invalidate the whole region
2215 dirty = visibleRegion;
2216 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002217 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218 layer->contentDirty = false;
2219 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002220 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002221 * the exposed region consists of two components:
2222 * 1) what's VISIBLE now and was COVERED before
2223 * 2) what's EXPOSED now less what was EXPOSED before
2224 *
2225 * note that (1) is conservative, we start with the whole
2226 * visible region but only keep what used to be covered by
2227 * something -- which mean it may have been exposed.
2228 *
2229 * (2) handles areas that were not covered by anything but got
2230 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002231 */
Mathias Agopianab028732010-03-16 16:41:46 -07002232 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002233 const Region oldVisibleRegion = layer->visibleRegion;
2234 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002235 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2236 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 }
2238 dirty.subtractSelf(aboveOpaqueLayers);
2239
2240 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002241 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002242
Mathias Agopianab028732010-03-16 16:41:46 -07002243 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002245
Jesse Halla8026d22012-09-25 13:25:04 -07002246 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247 layer->setVisibleRegion(visibleRegion);
2248 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002249 layer->setVisibleNonTransparentRegion(
2250 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002251 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252
Mathias Agopian87baae12012-07-31 12:38:26 -07002253 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002254}
2255
Mathias Agopian87baae12012-07-31 12:38:26 -07002256void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2257 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002258 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002259 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2260 if (hw->getLayerStack() == layerStack) {
2261 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002262 }
2263 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002264}
2265
Dan Stoza6b9454d2014-11-07 16:00:59 -08002266bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002267{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002268 ALOGV("handlePageFlip");
2269
Brian Andersond6927fb2016-07-23 23:37:30 -07002270 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002271
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002273 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002274
2275 // Store the set of layers that need updates. This set must not change as
2276 // buffers are being latched, as this could result in a deadlock.
2277 // Example: Two producers share the same command stream and:
2278 // 1.) Layer 0 is latched
2279 // 2.) Layer 0 gets a new frame
2280 // 2.) Layer 1 gets a new frame
2281 // 3.) Layer 1 is latched.
2282 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2283 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002284 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002285 if (layer->hasQueuedFrame()) {
2286 frameQueued = true;
2287 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002288 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002289 } else {
2290 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002291 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002292 } else {
2293 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002294 }
Robert Carr2047fae2016-11-28 14:09:09 -08002295 });
2296
Dan Stoza9e56aa02015-11-02 13:00:03 -08002297 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002298 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002299 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002301 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002302
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002303 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002304
2305 // If we will need to wake up at some time in the future to deal with a
2306 // queued frame that shouldn't be displayed during this vsync period, wake
2307 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002308 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002309 signalLayerUpdate();
2310 }
2311
2312 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002313 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314}
2315
Mathias Agopianad456f92011-01-13 17:53:01 -08002316void SurfaceFlinger::invalidateHwcGeometry()
2317{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002318 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002319}
2320
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002321
Fabien Sanglard830b8472016-11-30 16:35:58 -08002322void SurfaceFlinger::doDisplayComposition(
2323 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002324 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002325{
Dan Stoza71433162014-02-04 16:22:36 -08002326 // We only need to actually compose the display if:
2327 // 1) It is being handled by hardware composer, which may need this to
2328 // keep its virtual display state machine in sync, or
2329 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002330 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002331 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002332 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002333 return;
2334 }
2335
Dan Stoza9e56aa02015-11-02 13:00:03 -08002336 ALOGV("doDisplayComposition");
2337
Mathias Agopian87baae12012-07-31 12:38:26 -07002338 Region dirtyRegion(inDirtyRegion);
2339
Mathias Agopianb8a55602009-06-26 19:06:36 -07002340 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002341 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342
Fabien Sanglard830b8472016-11-30 16:35:58 -08002343 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002344 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002345 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2346 // takes a rectangle, we must make sure to update that whole
2347 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002348 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002349 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002350 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002351 // We need to redraw the rectangle that will be updated
2352 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002353 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002354 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002355 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002356 } else {
2357 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002358 dirtyRegion.set(displayDevice->bounds());
2359 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 }
2361 }
2362
Fabien Sanglard830b8472016-11-30 16:35:58 -08002363 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002365 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002366 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002367
2368 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002369 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370}
2371
Dan Stoza9e56aa02015-11-02 13:00:03 -08002372bool SurfaceFlinger::doComposeSurfaces(
2373 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002374{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002376
Dan Stoza9e56aa02015-11-02 13:00:03 -08002377 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002378
2379 mat4 oldColorMatrix;
2380 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2381 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2382 if (applyColorMatrix) {
2383 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2384 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2385 }
2386
Dan Stoza9e56aa02015-11-02 13:00:03 -08002387 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2388 if (hasClientComposition) {
2389 ALOGV("hasClientComposition");
2390
2391 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002392 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002394 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2395 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2396 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2397 }
2398 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002399 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002400
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002401 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002402 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2403 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002404 // when using overlays, we assume a fully transparent framebuffer
2405 // NOTE: we could reduce how much we need to clear, for instance
2406 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002407 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002408 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002409 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002410 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002411 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002413
2414 // we remove the scissor part
2415 // we're left with the letterbox region
2416 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002417 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002418
2419 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002421
2422 // but limit it to the dirty region
2423 region.andSelf(dirty);
2424
Mathias Agopianb9494d52012-04-18 02:28:45 -07002425 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002426 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002427 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002428 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002429 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002430 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002431
Dan Stoza9e56aa02015-11-02 13:00:03 -08002432 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002433 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002434 // scissor on the main display. It should never be needed
2435 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 const Rect& bounds(displayDevice->getBounds());
2437 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002438 if (scissor != bounds) {
2439 // scissor doesn't match the screen's dimensions, so we
2440 // need to clear everything outside of it and enable
2441 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002442
Mathias Agopianf45c5102012-10-24 16:29:17 -07002443 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 const uint32_t height = displayDevice->getHeight();
2445 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002446 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002447 }
2448 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002449 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002450
Mathias Agopian85d751c2012-08-29 16:59:24 -07002451 /*
2452 * and then, render the layers targeted at the framebuffer
2453 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002454
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 ALOGV("Rendering client layers");
2456 const Transform& displayTransform = displayDevice->getTransform();
2457 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002458 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002459 bool firstLayer = true;
2460 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2461 const Region clip(dirty.intersect(
2462 displayTransform.transform(layer->visibleRegion)));
2463 ALOGV("Layer: %s", layer->getName().string());
2464 ALOGV(" Composition type: %s",
2465 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002466 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 switch (layer->getCompositionType(hwcId)) {
2468 case HWC2::Composition::Cursor:
2469 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002470 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002472 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002473 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2474 layer->isOpaque(state) && (state.alpha == 1.0f)
2475 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002476 // never clear the very first layer since we're
2477 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002478 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002479 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002480 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002481 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 case HWC2::Composition::Client: {
2483 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002484 break;
2485 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002487 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002488 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 } else {
2490 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002491 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002492 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002493 }
2494 } else {
2495 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002496 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002497 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002499 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002500 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002501 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002502 }
2503 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002504
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002505 if (applyColorMatrix) {
2506 getRenderEngine().setupColorTransform(oldColorMatrix);
2507 }
2508
Mathias Agopianf45c5102012-10-24 16:29:17 -07002509 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002510 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002511 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512}
2513
Fabien Sanglard830b8472016-11-30 16:35:58 -08002514void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2515 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002516 RenderEngine& engine(getRenderEngine());
2517 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518}
2519
Dan Stoza7d89d062015-04-30 13:29:25 -07002520status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002521 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002522 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002523 const sp<Layer>& lbc,
2524 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002525{
Dan Stoza7d89d062015-04-30 13:29:25 -07002526 // add this layer to the current state list
2527 {
2528 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002529 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002530 return NO_MEMORY;
2531 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002532 if (parent == nullptr) {
2533 mCurrentState.layersSortedByZ.add(lbc);
2534 } else {
2535 parent->addChild(lbc);
2536 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002537 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002538 mLayersAdded = true;
2539 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002540 }
2541
Mathias Agopian96f08192010-06-02 23:28:45 -07002542 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002543 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002544
Dan Stoza7d89d062015-04-30 13:29:25 -07002545 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002546}
2547
Robert Carr9524cb32017-02-13 11:32:32 -08002548status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002549 const auto& p = layer->getParent();
2550 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2551 mCurrentState.layersSortedByZ.remove(layer);
2552
Robert Carr136e2f62017-02-08 17:54:29 -08002553 // As a matter of normal operation, the LayerCleaner will produce a second
2554 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2555 // so we will succeed in promoting it, but it's already been removed
2556 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2557 // otherwise something has gone wrong and we are leaking the layer.
2558 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002559 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2560 layer->getName().string(),
2561 (p != nullptr) ? p->getName().string() : "no-parent");
2562 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002563 } else if (index < 0) {
2564 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002565 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002566
2567 mLayersPendingRemoval.add(layer);
2568 mLayersRemoved = true;
2569 mNumLayers--;
2570 setTransactionFlags(eTransactionNeeded);
2571 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572}
2573
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002574uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002575 return android_atomic_release_load(&mTransactionFlags);
2576}
2577
Mathias Agopian3f844832013-08-07 21:24:32 -07002578uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2580}
2581
Mathias Agopian3f844832013-08-07 21:24:32 -07002582uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2584 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002585 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002586 }
2587 return old;
2588}
2589
Mathias Agopian8b33f032012-07-24 20:43:54 -07002590void SurfaceFlinger::setTransactionState(
2591 const Vector<ComposerState>& state,
2592 const Vector<DisplayState>& displays,
2593 uint32_t flags)
2594{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002595 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002596 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002597 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002598
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002599 if (flags & eAnimation) {
2600 // For window updates that are part of an animation we must wait for
2601 // previous animation "frames" to be handled.
2602 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002603 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002604 if (CC_UNLIKELY(err != NO_ERROR)) {
2605 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002606 // caller after a few seconds.
2607 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2608 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002609 mAnimTransactionPending = false;
2610 break;
2611 }
2612 }
2613 }
2614
Mathias Agopiane57f2922012-08-09 16:29:12 -07002615 size_t count = displays.size();
2616 for (size_t i=0 ; i<count ; i++) {
2617 const DisplayState& s(displays[i]);
2618 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002619 }
2620
Mathias Agopiane57f2922012-08-09 16:29:12 -07002621 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002622 for (size_t i=0 ; i<count ; i++) {
2623 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002624 // Here we need to check that the interface we're given is indeed
2625 // one of our own. A malicious client could give us a NULL
2626 // IInterface, or one of its own or even one of our own but a
2627 // different type. All these situations would cause us to crash.
2628 //
2629 // NOTE: it would be better to use RTTI as we could directly check
2630 // that we have a Client*. however, RTTI is disabled in Android.
2631 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002632 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002633 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002634 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002635 sp<Client> client( static_cast<Client *>(s.client.get()) );
2636 transactionFlags |= setClientStateLocked(client, s.state);
2637 }
2638 }
2639 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002640 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002641
Robert Carr2a7dbb42016-05-24 11:41:28 -07002642 // If a synchronous transaction is explicitly requested without any changes,
2643 // force a transaction anyway. This can be used as a flush mechanism for
2644 // previous async transactions.
2645 if (transactionFlags == 0 && (flags & eSynchronous)) {
2646 transactionFlags = eTransactionNeeded;
2647 }
2648
Mathias Agopian386aa982011-11-07 21:58:03 -08002649 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002650 if (mInterceptor.isEnabled()) {
2651 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2652 }
Irvel468051e2016-06-13 16:44:44 -07002653
Mathias Agopian386aa982011-11-07 21:58:03 -08002654 // this triggers the transaction
2655 setTransactionFlags(transactionFlags);
2656
2657 // if this is a synchronous transaction, wait for it to take effect
2658 // before returning.
2659 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002660 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002661 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002662 if (flags & eAnimation) {
2663 mAnimTransactionPending = true;
2664 }
2665 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002666 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2667 if (CC_UNLIKELY(err != NO_ERROR)) {
2668 // just in case something goes wrong in SF, return to the
2669 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002670 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2671 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002672 break;
2673 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 }
2676}
2677
Mathias Agopiane57f2922012-08-09 16:29:12 -07002678uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2679{
Jesse Hall9a143922012-10-04 16:29:19 -07002680 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2681 if (dpyIdx < 0)
2682 return 0;
2683
Mathias Agopiane57f2922012-08-09 16:29:12 -07002684 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002685 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002686 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002687 const uint32_t what = s.what;
2688 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002689 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002690 disp.surface = s.surface;
2691 flags |= eDisplayTransactionNeeded;
2692 }
2693 }
2694 if (what & DisplayState::eLayerStackChanged) {
2695 if (disp.layerStack != s.layerStack) {
2696 disp.layerStack = s.layerStack;
2697 flags |= eDisplayTransactionNeeded;
2698 }
2699 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002700 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002701 if (disp.orientation != s.orientation) {
2702 disp.orientation = s.orientation;
2703 flags |= eDisplayTransactionNeeded;
2704 }
2705 if (disp.frame != s.frame) {
2706 disp.frame = s.frame;
2707 flags |= eDisplayTransactionNeeded;
2708 }
2709 if (disp.viewport != s.viewport) {
2710 disp.viewport = s.viewport;
2711 flags |= eDisplayTransactionNeeded;
2712 }
2713 }
Michael Lentine47e45402014-07-18 15:34:25 -07002714 if (what & DisplayState::eDisplaySizeChanged) {
2715 if (disp.width != s.width) {
2716 disp.width = s.width;
2717 flags |= eDisplayTransactionNeeded;
2718 }
2719 if (disp.height != s.height) {
2720 disp.height = s.height;
2721 flags |= eDisplayTransactionNeeded;
2722 }
2723 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002724 }
2725 return flags;
2726}
2727
2728uint32_t SurfaceFlinger::setClientStateLocked(
2729 const sp<Client>& client,
2730 const layer_state_t& s)
2731{
2732 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002733 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002734 if (layer != 0) {
2735 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002736 bool geometryAppliesWithResize =
2737 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002738 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002739 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002740 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002741 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002742 }
2743 if (what & layer_state_t::eLayerChanged) {
2744 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745 const auto& p = layer->getParent();
2746 if (p == nullptr) {
2747 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2748 if (layer->setLayer(s.z) && idx >= 0) {
2749 mCurrentState.layersSortedByZ.removeAt(idx);
2750 mCurrentState.layersSortedByZ.add(layer);
2751 // we need traversal (state changed)
2752 // AND transaction (list changed)
2753 flags |= eTransactionNeeded|eTraversalNeeded;
2754 }
2755 } else {
2756 if (p->setChildLayer(layer, s.z)) {
2757 flags |= eTransactionNeeded|eTraversalNeeded;
2758 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759 }
2760 }
2761 if (what & layer_state_t::eSizeChanged) {
2762 if (layer->setSize(s.w, s.h)) {
2763 flags |= eTraversalNeeded;
2764 }
2765 }
2766 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002767 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002768 flags |= eTraversalNeeded;
2769 }
2770 if (what & layer_state_t::eMatrixChanged) {
2771 if (layer->setMatrix(s.matrix))
2772 flags |= eTraversalNeeded;
2773 }
2774 if (what & layer_state_t::eTransparentRegionChanged) {
2775 if (layer->setTransparentRegionHint(s.transparentRegion))
2776 flags |= eTraversalNeeded;
2777 }
Dan Stoza23116082015-06-18 14:58:39 -07002778 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002779 if (layer->setFlags(s.flags, s.mask))
2780 flags |= eTraversalNeeded;
2781 }
2782 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002783 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002784 flags |= eTraversalNeeded;
2785 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002786 if (what & layer_state_t::eFinalCropChanged) {
2787 if (layer->setFinalCrop(s.finalCrop))
2788 flags |= eTraversalNeeded;
2789 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002790 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 // We only allow setting layer stacks for top level layers,
2793 // everything else inherits layer stack from its parent.
2794 if (layer->hasParent()) {
2795 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2796 layer->getName().string());
2797 } else if (idx < 0) {
2798 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2799 "that also does not appear in the top level layer list. Something"
2800 " has gone wrong.", layer->getName().string());
2801 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002802 mCurrentState.layersSortedByZ.removeAt(idx);
2803 mCurrentState.layersSortedByZ.add(layer);
2804 // we need traversal (state changed)
2805 // AND transaction (list changed)
2806 flags |= eTransactionNeeded|eTraversalNeeded;
2807 }
2808 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002809 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002810 if (s.barrierHandle != nullptr) {
2811 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2812 } else if (s.barrierGbp != nullptr) {
2813 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2814 if (authenticateSurfaceTextureLocked(gbp)) {
2815 const auto& otherLayer =
2816 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2817 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2818 } else {
2819 ALOGE("Attempt to defer transaction to to an"
2820 " unrecognized GraphicBufferProducer");
2821 }
2822 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002823 // We don't trigger a traversal here because if no other state is
2824 // changed, we don't want this to cause any more work
2825 }
Robert Carr1db73f62016-12-21 12:58:51 -08002826 if (what & layer_state_t::eReparentChildren) {
2827 if (layer->reparentChildren(s.reparentHandle)) {
2828 flags |= eTransactionNeeded|eTraversalNeeded;
2829 }
2830 }
Robert Carr9524cb32017-02-13 11:32:32 -08002831 if (what & layer_state_t::eDetachChildren) {
2832 layer->detachChildren();
2833 }
Robert Carrc3574f72016-03-24 12:19:32 -07002834 if (what & layer_state_t::eOverrideScalingModeChanged) {
2835 layer->setOverrideScalingMode(s.overrideScalingMode);
2836 // We don't trigger a traversal here because if no other state is
2837 // changed, we don't want this to cause any more work
2838 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002839 }
2840 return flags;
2841}
2842
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002843status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002844 const String8& name,
2845 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002846 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002847 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2848 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002850 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002851 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002852 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002853 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002854 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002855
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002856 status_t result = NO_ERROR;
2857
2858 sp<Layer> layer;
2859
Mathias Agopian3165cc22012-08-08 19:42:09 -07002860 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2861 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002862 result = createNormalLayer(client,
2863 name, w, h, flags, format,
2864 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002866 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002867 result = createDimLayer(client,
2868 name, w, h, flags,
2869 handle, gbp, &layer);
2870 break;
2871 default:
2872 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873 break;
2874 }
2875
Dan Stoza7d89d062015-04-30 13:29:25 -07002876 if (result != NO_ERROR) {
2877 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002879
Albert Chaulk479c60c2017-01-27 14:21:34 -05002880 layer->setInfo(windowType, ownerUid);
2881
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002883 if (result != NO_ERROR) {
2884 return result;
2885 }
Irvelffc9efc2016-07-27 15:16:37 -07002886 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002887
2888 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002889 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890}
2891
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002892status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2893 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2894 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002895{
2896 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002897 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 case PIXEL_FORMAT_TRANSPARENT:
2899 case PIXEL_FORMAT_TRANSLUCENT:
2900 format = PIXEL_FORMAT_RGBA_8888;
2901 break;
2902 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002903 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 break;
2905 }
2906
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002907 *outLayer = new Layer(this, client, name, w, h, flags);
2908 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2909 if (err == NO_ERROR) {
2910 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002911 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002913
2914 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2915 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916}
2917
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002918status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2919 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2920 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002922 *outLayer = new LayerDim(this, client, name, w, h, flags);
2923 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002924 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002925 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002926}
2927
Mathias Agopianac9fa422013-02-11 16:40:36 -08002928status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929{
Robert Carr9524cb32017-02-13 11:32:32 -08002930 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07002931 status_t err = NO_ERROR;
2932 sp<Layer> l(client->getLayerUser(handle));
2933 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002934 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002935 err = removeLayer(l);
2936 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2937 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002938 }
2939 return err;
2940}
2941
Mathias Agopian13127d82013-03-05 17:47:11 -08002942status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002943{
Mathias Agopian67106042013-03-14 19:18:13 -07002944 // called by ~LayerCleaner() when all references to the IBinder (handle)
2945 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002946 sp<Layer> l = layer.promote();
2947 if (l == nullptr) {
2948 // The layer has already been removed, carry on
2949 return NO_ERROR;
2950 } if (l->getParent() != nullptr) {
2951 // If we have a parent, then we can continue to live as long as it does.
2952 return NO_ERROR;
2953 }
2954 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955}
2956
Mathias Agopianb60314a2012-04-10 22:09:54 -07002957// ---------------------------------------------------------------------------
2958
Andy McFadden13a082e2012-08-24 10:16:42 -07002959void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002960 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002961 Vector<ComposerState> state;
2962 Vector<DisplayState> displays;
2963 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002964 d.what = DisplayState::eDisplayProjectionChanged |
2965 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002966 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002967 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002968 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002969 d.frame.makeInvalid();
2970 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002971 d.width = 0;
2972 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002973 displays.add(d);
2974 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002975 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002976
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2978 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002979 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002980
2981 {
2982 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
2983 mCompositorTiming.interval = period;
2984 }
Andy McFadden13a082e2012-08-24 10:16:42 -07002985}
2986
2987void SurfaceFlinger::initializeDisplays() {
2988 class MessageScreenInitialized : public MessageBase {
2989 SurfaceFlinger* flinger;
2990 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002991 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002992 virtual bool handler() {
2993 flinger->onInitializeDisplays();
2994 return true;
2995 }
2996 };
2997 sp<MessageBase> msg = new MessageScreenInitialized(this);
2998 postMessageAsync(msg); // we may be called from main thread, use async message
2999}
3000
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003001void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3002 int mode) {
3003 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3004 this);
3005 int32_t type = hw->getDisplayType();
3006 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003007
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003008 if (mode == currentMode) {
3009 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003010 return;
3011 }
3012
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003013 hw->setPowerMode(mode);
3014 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3015 ALOGW("Trying to set power mode for virtual display");
3016 return;
3017 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003018
Irvelffc9efc2016-07-27 15:16:37 -07003019 if (mInterceptor.isEnabled()) {
3020 Mutex::Autolock _l(mStateLock);
3021 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3022 if (idx < 0) {
3023 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3024 return;
3025 }
3026 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3027 }
3028
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003029 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003030 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003031 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003032 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3033 // FIXME: eventthread only knows about the main display right now
3034 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003035 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003036 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003038 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003039 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003040 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003041
3042 struct sched_param param = {0};
3043 param.sched_priority = 1;
3044 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3045 ALOGW("Couldn't set SCHED_FIFO on display on");
3046 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003047 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003048 // Turn off the display
3049 struct sched_param param = {0};
3050 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3051 ALOGW("Couldn't set SCHED_OTHER on display off");
3052 }
3053
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003054 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003055 disableHardwareVsync(true); // also cancels any in-progress resync
3056
Mathias Agopiancde87a32012-09-13 14:09:01 -07003057 // FIXME: eventthread only knows about the main display right now
3058 mEventThread->onScreenReleased();
3059 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003060
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003061 getHwComposer().setPowerMode(type, mode);
3062 mVisibleRegionsDirty = true;
3063 // from this point on, SF will stop drawing on this display
3064 } else {
3065 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003066 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003067}
3068
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003069void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3070 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003071 SurfaceFlinger& mFlinger;
3072 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003073 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003074 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003075 MessageSetPowerMode(SurfaceFlinger& flinger,
3076 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3077 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003078 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003079 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003080 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003081 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003082 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003083 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003084 ALOGW("Attempt to set power mode = %d for virtual display",
3085 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003086 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003087 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003088 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003089 return true;
3090 }
3091 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003092 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003093 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003094}
3095
3096// ---------------------------------------------------------------------------
3097
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3099{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003101
Mathias Agopianbd115332013-04-18 16:41:04 -07003102 IPCThreadState* ipc = IPCThreadState::self();
3103 const int pid = ipc->getCallingPid();
3104 const int uid = ipc->getCallingUid();
3105 if ((uid != AID_SHELL) &&
3106 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003107 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003108 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003110 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003111 // (this would indicate SF is stuck, but we want to be able to
3112 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003113 status_t err = mStateLock.timedLock(s2ns(1));
3114 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003115 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003116 result.appendFormat(
3117 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3118 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003119 }
3120
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003121 bool dumpAll = true;
3122 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003123 size_t numArgs = args.size();
3124 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003125 if ((index < numArgs) &&
3126 (args[index] == String16("--list"))) {
3127 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003128 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003129 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003130 }
3131
3132 if ((index < numArgs) &&
3133 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003134 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003135 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003136 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003137 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003138
3139 if ((index < numArgs) &&
3140 (args[index] == String16("--latency-clear"))) {
3141 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003142 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003143 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003144 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003145
3146 if ((index < numArgs) &&
3147 (args[index] == String16("--dispsync"))) {
3148 index++;
3149 mPrimaryDispSync.dump(result);
3150 dumpAll = false;
3151 }
Dan Stozab90cf072015-03-05 11:05:59 -08003152
3153 if ((index < numArgs) &&
3154 (args[index] == String16("--static-screen"))) {
3155 index++;
3156 dumpStaticScreenStats(result);
3157 dumpAll = false;
3158 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003159
3160 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003161 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003162 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003163 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003164 dumpAll = false;
3165 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003167
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003168 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003169 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003170 }
3171
Mathias Agopian9795c422009-08-26 16:36:26 -07003172 if (locked) {
3173 mStateLock.unlock();
3174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 }
3176 write(fd, result.string(), result.size());
3177 return NO_ERROR;
3178}
3179
Dan Stozac7014012014-02-14 15:03:43 -08003180void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3181 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003182{
Robert Carr2047fae2016-11-28 14:09:09 -08003183 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003184 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003185 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003186}
3187
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003188void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003189 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003190{
3191 String8 name;
3192 if (index < args.size()) {
3193 name = String8(args[index]);
3194 index++;
3195 }
3196
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3198 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003199 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003200
3201 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003202 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003203 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003204 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003205 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003206 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003207 }
Robert Carr2047fae2016-11-28 14:09:09 -08003208 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003209 }
3210}
3211
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003212void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003213 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003214{
3215 String8 name;
3216 if (index < args.size()) {
3217 name = String8(args[index]);
3218 index++;
3219 }
3220
Robert Carr2047fae2016-11-28 14:09:09 -08003221 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003222 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003223 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003224 }
Robert Carr2047fae2016-11-28 14:09:09 -08003225 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003226
Svetoslavd85084b2014-03-20 10:28:31 -07003227 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003228}
3229
Jamie Gennis6547ff42013-07-16 20:12:42 -07003230// This should only be called from the main thread. Otherwise it would need
3231// the lock and should use mCurrentState rather than mDrawingState.
3232void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003233 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003234 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003235 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003236
3237 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3238}
3239
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003240void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003241{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003242 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07003243#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003244 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07003245#endif
3246#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003247 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003248#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003249 if (isLayerTripleBufferingDisabled())
3250 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003251 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003252}
3253
Dan Stozab90cf072015-03-05 11:05:59 -08003254void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3255{
3256 result.appendFormat("Static screen stats:\n");
3257 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3258 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3259 float percent = 100.0f *
3260 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3261 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3262 b + 1, bucketTimeSec, percent);
3263 }
3264 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3265 float percent = 100.0f *
3266 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3267 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3268 NUM_BUCKETS - 1, bucketTimeSec, percent);
3269}
3270
Dan Stozae77c7662016-05-13 11:37:28 -07003271void SurfaceFlinger::recordBufferingStats(const char* layerName,
3272 std::vector<OccupancyTracker::Segment>&& history) {
3273 Mutex::Autolock lock(mBufferingStatsMutex);
3274 auto& stats = mBufferingStats[layerName];
3275 for (const auto& segment : history) {
3276 if (!segment.usedThirdBuffer) {
3277 stats.twoBufferTime += segment.totalTime;
3278 }
3279 if (segment.occupancyAverage < 1.0f) {
3280 stats.doubleBufferedTime += segment.totalTime;
3281 } else if (segment.occupancyAverage < 2.0f) {
3282 stats.tripleBufferedTime += segment.totalTime;
3283 }
3284 ++stats.numSegments;
3285 stats.totalTime += segment.totalTime;
3286 }
3287}
3288
Brian Andersond6927fb2016-07-23 23:37:30 -07003289void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3290 result.appendFormat("Layer frame timestamps:\n");
3291
3292 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3293 const size_t count = currentLayers.size();
3294 for (size_t i=0 ; i<count ; i++) {
3295 currentLayers[i]->dumpFrameEvents(result);
3296 }
3297}
3298
Dan Stozae77c7662016-05-13 11:37:28 -07003299void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3300 result.append("Buffering stats:\n");
3301 result.append(" [Layer name] <Active time> <Two buffer> "
3302 "<Double buffered> <Triple buffered>\n");
3303 Mutex::Autolock lock(mBufferingStatsMutex);
3304 typedef std::tuple<std::string, float, float, float> BufferTuple;
3305 std::map<float, BufferTuple, std::greater<float>> sorted;
3306 for (const auto& statsPair : mBufferingStats) {
3307 const char* name = statsPair.first.c_str();
3308 const BufferingStats& stats = statsPair.second;
3309 if (stats.numSegments == 0) {
3310 continue;
3311 }
3312 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3313 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3314 stats.totalTime;
3315 float doubleBufferRatio = static_cast<float>(
3316 stats.doubleBufferedTime) / stats.totalTime;
3317 float tripleBufferRatio = static_cast<float>(
3318 stats.tripleBufferedTime) / stats.totalTime;
3319 sorted.insert({activeTime, {name, twoBufferRatio,
3320 doubleBufferRatio, tripleBufferRatio}});
3321 }
3322 for (const auto& sortedPair : sorted) {
3323 float activeTime = sortedPair.first;
3324 const BufferTuple& values = sortedPair.second;
3325 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3326 std::get<0>(values).c_str(), activeTime,
3327 std::get<1>(values), std::get<2>(values),
3328 std::get<3>(values));
3329 }
3330 result.append("\n");
3331}
3332
3333
Mathias Agopian74d211a2013-04-22 16:55:35 +02003334void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3335 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003336{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003337 bool colorize = false;
3338 if (index < args.size()
3339 && (args[index] == String16("--color"))) {
3340 colorize = true;
3341 index++;
3342 }
3343
3344 Colorizer colorizer(colorize);
3345
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003346 // figure out if we're stuck somewhere
3347 const nsecs_t now = systemTime();
3348 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3349 const nsecs_t inTransaction(mDebugInTransaction);
3350 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3351 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3352
3353 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003354 * Dump library configuration.
3355 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003356
3357 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003358 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003359 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003360 appendSfConfigString(result);
3361 appendUiConfigString(result);
3362 appendGuiConfigString(result);
3363 result.append("\n");
3364
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003365 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003366 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003367 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003368 result.append(SyncFeatures::getInstance().toString());
3369 result.append("\n");
3370
Dan Stoza9e56aa02015-11-02 13:00:03 -08003371 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3372
Andy McFadden41d67d72014-04-25 16:58:34 -07003373 colorizer.bold(result);
3374 result.append("DispSync configuration: ");
3375 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003376 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3377 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3379 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003380 result.append("\n");
3381
Dan Stozab90cf072015-03-05 11:05:59 -08003382 // Dump static screen stats
3383 result.append("\n");
3384 dumpStaticScreenStats(result);
3385 result.append("\n");
3386
Dan Stozae77c7662016-05-13 11:37:28 -07003387 dumpBufferingStats(result);
3388
Andy McFadden4803b742012-09-24 19:07:20 -07003389 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003390 * Dump the visible layer list
3391 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003392 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003393 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003394 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003395 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003396 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003397 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003398
3399 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003400 * Dump Display state
3401 */
3402
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003403 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003404 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003405 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003406 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3407 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003408 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003409 }
3410
3411 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412 * Dump SurfaceFlinger global state
3413 */
3414
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003415 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003416 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003417 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418
Mathias Agopian888c8222012-08-04 21:10:38 -07003419 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003420 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003421
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003422 colorizer.bold(result);
3423 result.appendFormat("EGL implementation : %s\n",
3424 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3425 colorizer.reset(result);
3426 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003427 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003428
Mathias Agopian875d8e12013-06-07 15:35:48 -07003429 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003430
Mathias Agopian42977342012-08-05 00:40:46 -07003431 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003432 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3433 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003434 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003435 " last eglSwapBuffers() time: %f us\n"
3436 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003437 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438 " refresh-rate : %f fps\n"
3439 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003440 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003441 " gpu_to_cpu_unsupported : %d\n"
3442 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443 mLastSwapBufferTime/1000.0,
3444 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003445 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003446 1e9 / activeConfig->getVsyncPeriod(),
3447 activeConfig->getDpiX(),
3448 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003449 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003450
Mathias Agopian74d211a2013-04-22 16:55:35 +02003451 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003452 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003453
Mathias Agopian74d211a2013-04-22 16:55:35 +02003454 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003455 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456
3457 /*
3458 * VSYNC state
3459 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003460 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003461 result.append("\n");
3462
3463 /*
3464 * HWC layer minidump
3465 */
3466 for (size_t d = 0; d < mDisplays.size(); d++) {
3467 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3468 int32_t hwcId = displayDevice->getHwcDisplayId();
3469 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3470 continue;
3471 }
3472
3473 result.appendFormat("Display %d HWC layers:\n", hwcId);
3474 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003475 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003476 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003477 });
Dan Stozae22aec72016-08-01 13:20:59 -07003478 result.append("\n");
3479 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003480
3481 /*
3482 * Dump HWComposer state
3483 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003484 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003485 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003486 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003487 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003488 result.appendFormat(" h/w composer %s\n",
3489 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003490 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003491
3492 /*
3493 * Dump gralloc state
3494 */
3495 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3496 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003497}
3498
Mathias Agopian13127d82013-03-05 17:47:11 -08003499const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003500SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003501 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003502 wp<IBinder> dpy;
3503 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3504 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3505 dpy = mDisplays.keyAt(i);
3506 break;
3507 }
3508 }
3509 if (dpy == NULL) {
3510 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3511 // Just use the primary display so we have something to return
3512 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3513 }
3514 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003515}
3516
Keun young Park63f165f2012-08-31 10:53:36 -07003517bool SurfaceFlinger::startDdmConnection()
3518{
3519 void* libddmconnection_dso =
3520 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3521 if (!libddmconnection_dso) {
3522 return false;
3523 }
3524 void (*DdmConnection_start)(const char* name);
3525 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003526 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003527 if (!DdmConnection_start) {
3528 dlclose(libddmconnection_dso);
3529 return false;
3530 }
3531 (*DdmConnection_start)(getServiceName());
3532 return true;
3533}
3534
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003535status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 switch (code) {
3537 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003538 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003539 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003540 case CLEAR_ANIMATION_FRAME_STATS:
3541 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003542 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003543 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003544 {
3545 // codes that require permission check
3546 IPCThreadState* ipc = IPCThreadState::self();
3547 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003548 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003549 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003550 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003551 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003552 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003554 break;
3555 }
Robert Carr1db73f62016-12-21 12:58:51 -08003556 /*
3557 * Calling setTransactionState is safe, because you need to have been
3558 * granted a reference to Client* and Handle* to do anything with it.
3559 *
3560 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3561 */
3562 case SET_TRANSACTION_STATE:
3563 case CREATE_SCOPED_CONNECTION:
3564 {
3565 return OK;
3566 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003567 case CAPTURE_SCREEN:
3568 {
3569 // codes that require permission check
3570 IPCThreadState* ipc = IPCThreadState::self();
3571 const int pid = ipc->getCallingPid();
3572 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003573 if ((uid != AID_GRAPHICS) &&
3574 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003575 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003576 return PERMISSION_DENIED;
3577 }
3578 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579 }
3580 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003581 return OK;
3582}
3583
3584status_t SurfaceFlinger::onTransact(
3585 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3586{
3587 status_t credentialCheck = CheckTransactCodeCredentials(code);
3588 if (credentialCheck != OK) {
3589 return credentialCheck;
3590 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003592 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3593 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003594 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003595 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003596 IPCThreadState* ipc = IPCThreadState::self();
3597 const int pid = ipc->getCallingPid();
3598 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003599 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003600 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003601 return PERMISSION_DENIED;
3602 }
3603 int n;
3604 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003605 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003606 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003607 return NO_ERROR;
3608 case 1002: // SHOW_UPDATES
3609 n = data.readInt32();
3610 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003611 invalidateHwcGeometry();
3612 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003614 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003615 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003616 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003618 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003619 setTransactionFlags(
3620 eTransactionNeeded|
3621 eDisplayTransactionNeeded|
3622 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003623 return NO_ERROR;
3624 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003625 case 1006:{ // send empty update
3626 signalRefresh();
3627 return NO_ERROR;
3628 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003629 case 1008: // toggle use of hw composer
3630 n = data.readInt32();
3631 mDebugDisableHWC = n ? 1 : 0;
3632 invalidateHwcGeometry();
3633 repaintEverything();
3634 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003635 case 1009: // toggle use of transform hint
3636 n = data.readInt32();
3637 mDebugDisableTransformHint = n ? 1 : 0;
3638 invalidateHwcGeometry();
3639 repaintEverything();
3640 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003642 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 reply->writeInt32(0);
3644 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003645 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003646 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003647 return NO_ERROR;
3648 case 1013: {
3649 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003650 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3651 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003652 return NO_ERROR;
3653 }
3654 case 1014: {
3655 // daltonize
3656 n = data.readInt32();
3657 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003658 case 1:
3659 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3660 break;
3661 case 2:
3662 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3663 break;
3664 case 3:
3665 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3666 break;
3667 default:
3668 mDaltonizer.setType(ColorBlindnessType::None);
3669 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003670 }
3671 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003672 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003673 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003674 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003675 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003676 invalidateHwcGeometry();
3677 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003678 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003679 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003680 case 1015: {
3681 // apply a color matrix
3682 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003683 if (n) {
3684 // color matrix is sent as mat3 matrix followed by vec3
3685 // offset, then packed into a mat4 where the last row is
3686 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003687 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003688 for (size_t j = 0; j < 4; j++) {
3689 mColorMatrix[i][j] = data.readFloat();
3690 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003691 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003692 } else {
3693 mColorMatrix = mat4();
3694 }
3695 invalidateHwcGeometry();
3696 repaintEverything();
3697 return NO_ERROR;
3698 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003699 // This is an experimental interface
3700 // Needs to be shifted to proper binder interface when we productize
3701 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003702 n = data.readInt32();
3703 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003704 return NO_ERROR;
3705 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003706 case 1017: {
3707 n = data.readInt32();
3708 mForceFullDamage = static_cast<bool>(n);
3709 return NO_ERROR;
3710 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003711 case 1018: { // Modify Choreographer's phase offset
3712 n = data.readInt32();
3713 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3714 return NO_ERROR;
3715 }
3716 case 1019: { // Modify SurfaceFlinger's phase offset
3717 n = data.readInt32();
3718 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3719 return NO_ERROR;
3720 }
Irvel468051e2016-06-13 16:44:44 -07003721 case 1020: { // Layer updates interceptor
3722 n = data.readInt32();
3723 if (n) {
3724 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003725 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003726 }
3727 else{
3728 ALOGV("Interceptor disabled");
3729 mInterceptor.disable();
3730 }
3731 return NO_ERROR;
3732 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003733 case 1021: { // Disable HWC virtual displays
3734 n = data.readInt32();
3735 mUseHwcVirtualDisplays = !n;
3736 return NO_ERROR;
3737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738 }
3739 }
3740 return err;
3741}
3742
Mathias Agopian53331da2011-08-22 21:44:41 -07003743void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003744 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003745 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003746}
3747
Mathias Agopian59119e62010-10-11 12:37:43 -07003748// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003749// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003750// ---------------------------------------------------------------------------
3751
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003752/* The code below is here to handle b/8734824
3753 *
3754 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003755 * from the surfaceflinger thread to the calling binder thread, where they
3756 * are executed. This allows the calling thread in the calling process to be
3757 * reused and not depend on having "enough" binder threads to handle the
3758 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003759 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003760class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003761 /* Parts of GraphicProducerWrapper are run on two different threads,
3762 * communicating by sending messages via Looper but also by shared member
3763 * data. Coherence maintenance is subtle and in places implicit (ugh).
3764 *
3765 * Don't rely on Looper's sendMessage/handleMessage providing
3766 * release/acquire semantics for any data not actually in the Message.
3767 * Data going from surfaceflinger to binder threads needs to be
3768 * synchronized explicitly.
3769 *
3770 * Barrier open/wait do provide release/acquire semantics. This provides
3771 * implicit synchronization for data coming back from binder to
3772 * surfaceflinger threads.
3773 */
3774
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003775 sp<IGraphicBufferProducer> impl;
3776 sp<Looper> looper;
3777 status_t result;
3778 bool exitPending;
3779 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003780 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003781 uint32_t code;
3782 Parcel const* data;
3783 Parcel* reply;
3784
3785 enum {
3786 MSG_API_CALL,
3787 MSG_EXIT
3788 };
3789
3790 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003791 * Called on surfaceflinger thread. This is called by our "fake"
3792 * BpGraphicBufferProducer. We package the data and reply Parcel and
3793 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003794 */
3795 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003796 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003797 this->code = code;
3798 this->data = &data;
3799 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003800 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003801 // if we've exited, we run the message synchronously right here.
3802 // note (JH): as far as I can tell from looking at the code, this
3803 // never actually happens. if it does, i'm not sure if it happens
3804 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003805 handleMessage(Message(MSG_API_CALL));
3806 } else {
3807 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003808 // Prevent stores to this->{code, data, reply} from being
3809 // reordered later than the construction of Message.
3810 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003811 looper->sendMessage(this, Message(MSG_API_CALL));
3812 barrier.wait();
3813 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003814 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003815 }
3816
3817 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003818 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003819 * call the real BpGraphicBufferProducer.
3820 */
3821 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003822 int what = message.what;
3823 // Prevent reads below from happening before the read from Message
3824 atomic_thread_fence(memory_order_acquire);
3825 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003826 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003827 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003828 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003829 exitRequested = true;
3830 }
3831 }
3832
3833public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003834 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003835 : impl(impl),
3836 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003837 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003838 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003839 exitRequested(false),
3840 code(0),
3841 data(NULL),
3842 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003843 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003844
Jesse Hallb154c422014-07-13 12:47:02 -07003845 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003846 status_t waitForResponse() {
3847 do {
3848 looper->pollOnce(-1);
3849 } while (!exitRequested);
3850 return result;
3851 }
3852
Jesse Hallb154c422014-07-13 12:47:02 -07003853 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003854 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003855 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003856 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003857 // Ensure this->result is visible to the binder thread before it
3858 // handles the message.
3859 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003860 looper->sendMessage(this, Message(MSG_EXIT));
3861 }
3862};
3863
3864
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003865status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3866 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003867 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003868 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003869 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003870
3871 if (CC_UNLIKELY(display == 0))
3872 return BAD_VALUE;
3873
3874 if (CC_UNLIKELY(producer == 0))
3875 return BAD_VALUE;
3876
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003877 // if we have secure windows on this display, never allow the screen capture
3878 // unless the producer interface is local (i.e.: we can take a screenshot for
3879 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003880 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003881
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003882 // Convert to surfaceflinger's internal rotation type.
3883 Transform::orientation_flags rotationFlags;
3884 switch (rotation) {
3885 case ISurfaceComposer::eRotateNone:
3886 rotationFlags = Transform::ROT_0;
3887 break;
3888 case ISurfaceComposer::eRotate90:
3889 rotationFlags = Transform::ROT_90;
3890 break;
3891 case ISurfaceComposer::eRotate180:
3892 rotationFlags = Transform::ROT_180;
3893 break;
3894 case ISurfaceComposer::eRotate270:
3895 rotationFlags = Transform::ROT_270;
3896 break;
3897 default:
3898 rotationFlags = Transform::ROT_0;
3899 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3900 break;
3901 }
3902
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003903 class MessageCaptureScreen : public MessageBase {
3904 SurfaceFlinger* flinger;
3905 sp<IBinder> display;
3906 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003907 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003908 uint32_t reqWidth, reqHeight;
3909 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003910 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003911 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003912 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003913 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003914 public:
3915 MessageCaptureScreen(SurfaceFlinger* flinger,
3916 const sp<IBinder>& display,
3917 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003918 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003919 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003920 bool useIdentityTransform,
3921 Transform::orientation_flags rotation,
3922 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003923 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003924 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003925 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003926 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003927 rotation(rotation), result(PERMISSION_DENIED),
3928 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003929 {
3930 }
3931 status_t getResult() const {
3932 return result;
3933 }
3934 virtual bool handler() {
3935 Mutex::Autolock _l(flinger->mStateLock);
3936 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003937 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003938 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003939 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003940 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003941 return true;
3942 }
3943 };
3944
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003945 // this creates a "fake" BBinder which will serve as a "fake" remote
3946 // binder to receive the marshaled calls and forward them to the
3947 // real remote (a BpGraphicBufferProducer)
3948 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3949
3950 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3951 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003952 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003953 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003954 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003955 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003956
3957 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003958 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003959 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003960 }
3961 return res;
3962}
3963
Mathias Agopian180f10d2013-04-10 22:55:41 -07003964
3965void SurfaceFlinger::renderScreenImplLocked(
3966 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003967 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003968 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003969 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003970{
3971 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003972 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003973
3974 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003975 const int32_t hw_w = hw->getWidth();
3976 const int32_t hw_h = hw->getHeight();
3977 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003978 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003979
Dan Stozac1879002014-05-22 15:59:05 -07003980 // if a default or invalid sourceCrop is passed in, set reasonable values
3981 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3982 !sourceCrop.isValid()) {
3983 sourceCrop.setLeftTop(Point(0, 0));
3984 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3985 }
3986
3987 // ensure that sourceCrop is inside screen
3988 if (sourceCrop.left < 0) {
3989 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3990 }
Dan Stozabe31f442014-06-11 11:20:54 -07003991 if (sourceCrop.right > hw_w) {
3992 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003993 }
3994 if (sourceCrop.top < 0) {
3995 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3996 }
Dan Stozabe31f442014-06-11 11:20:54 -07003997 if (sourceCrop.bottom > hw_h) {
3998 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003999 }
4000
Mathias Agopian180f10d2013-04-10 22:55:41 -07004001 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004002 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004003
4004 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004005 engine.setViewportAndProjection(
4006 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004007 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004008
4009 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004010 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004011
Robert Carr1f0a16a2016-10-24 16:27:39 -07004012 // We loop through the first level of layers without traversing,
4013 // as we need to interpret min/max layer Z in the top level Z space.
4014 for (const auto& layer : mDrawingState.layersSortedByZ) {
4015 if (layer->getLayerStack() != hw->getLayerStack()) {
4016 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004017 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004018 const Layer::State& state(layer->getDrawingState());
4019 if (state.z < minLayerZ || state.z > maxLayerZ) {
4020 continue;
4021 }
4022 layer->traverseInZOrder([&](Layer* layer) {
4023 if (!layer->isVisible()) {
4024 return;
4025 }
4026 if (filtering) layer->setFiltering(true);
4027 layer->draw(hw, useIdentityTransform);
4028 if (filtering) layer->setFiltering(false);
4029 });
4030 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004031
Mathias Agopian931bda12013-08-28 18:11:46 -07004032 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004033}
4034
4035
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004036status_t SurfaceFlinger::captureScreenImplLocked(
4037 const sp<const DisplayDevice>& hw,
4038 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004039 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004040 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004041 bool useIdentityTransform, Transform::orientation_flags rotation,
4042 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004043{
4044 ATRACE_CALL();
4045
Mathias Agopian180f10d2013-04-10 22:55:41 -07004046 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004047 uint32_t hw_w = hw->getWidth();
4048 uint32_t hw_h = hw->getHeight();
4049
4050 if (rotation & Transform::ROT_90) {
4051 std::swap(hw_w, hw_h);
4052 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004053
Mathias Agopian180f10d2013-04-10 22:55:41 -07004054 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4055 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4056 reqWidth, reqHeight, hw_w, hw_h);
4057 return BAD_VALUE;
4058 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004059
Mathias Agopian180f10d2013-04-10 22:55:41 -07004060 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4061 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4062
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004063 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004064 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004065 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004066 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4067 (state.z < minLayerZ || state.z > maxLayerZ)) {
4068 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004069 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004070 layer->traverseInZOrder([&](Layer *layer) {
4071 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4072 layer->isSecure());
4073 });
4074 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004075
4076 if (!isLocalScreenshot && secureLayerIsVisible) {
4077 ALOGW("FB is protected: PERMISSION_DENIED");
4078 return PERMISSION_DENIED;
4079 }
4080
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004081 // create a surface (because we're a producer, and we need to
4082 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004083 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004084
4085 // Put the screenshot Surface into async mode so that
4086 // Layer::headFenceHasSignaled will always return true and we'll latch the
4087 // first buffer regardless of whether or not its acquire fence has
4088 // signaled. This is needed to avoid a race condition in the rotation
4089 // animation. See b/30209608
4090 sur->setAsyncMode(true);
4091
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004092 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004093
Michael Lentine5a16a622015-05-21 13:48:24 -07004094 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4095 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004096 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4097 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004098
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004099 int err = 0;
4100 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004101 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004102 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4103 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004104
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004105 if (err == NO_ERROR) {
4106 ANativeWindowBuffer* buffer;
4107 /* TODO: Once we have the sync framework everywhere this can use
4108 * server-side waits on the fence that dequeueBuffer returns.
4109 */
4110 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4111 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004112 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004113 // create an EGLImage from the buffer so we can later
4114 // turn it into a texture
4115 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4116 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4117 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004118 // this binds the given EGLImage as a framebuffer for the
4119 // duration of this scope.
4120 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4121 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004122 // this will in fact render into our dequeued buffer
4123 // via an FBO, which means we didn't have to create
4124 // an EGLSurface and therefore we're not
4125 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004126 renderScreenImplLocked(
4127 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4128 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004129
Riley Andrews86639902014-08-15 12:27:24 -07004130 // Attempt to create a sync khr object that can produce a sync point. If that
4131 // isn't available, create a non-dupable sync object in the fallback path and
4132 // wait on it directly.
4133 EGLSyncKHR sync;
4134 if (!DEBUG_SCREENSHOTS) {
4135 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004136 // native fence fd will not be populated until flush() is done.
4137 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004138 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004139 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004140 }
Riley Andrews86639902014-08-15 12:27:24 -07004141 if (sync != EGL_NO_SYNC_KHR) {
4142 // get the sync fd
4143 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4144 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4145 ALOGW("captureScreen: failed to dup sync khr object");
4146 syncFd = -1;
4147 }
4148 eglDestroySyncKHR(mEGLDisplay, sync);
4149 } else {
4150 // fallback path
4151 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4152 if (sync != EGL_NO_SYNC_KHR) {
4153 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4154 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4155 EGLint eglErr = eglGetError();
4156 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4157 ALOGW("captureScreen: fence wait timed out");
4158 } else {
4159 ALOGW_IF(eglErr != EGL_SUCCESS,
4160 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4161 }
4162 eglDestroySyncKHR(mEGLDisplay, sync);
4163 } else {
4164 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4165 }
4166 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004167 if (DEBUG_SCREENSHOTS) {
4168 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4169 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4170 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4171 hw, minLayerZ, maxLayerZ);
4172 delete [] pixels;
4173 }
4174
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004175 } else {
4176 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4177 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004178 window->cancelBuffer(window, buffer, syncFd);
4179 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004180 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004181 // destroy our image
4182 eglDestroyImageKHR(mEGLDisplay, image);
4183 } else {
4184 result = BAD_VALUE;
4185 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004186 if (buffer) {
4187 // queueBuffer takes ownership of syncFd
4188 result = window->queueBuffer(window, buffer, syncFd);
4189 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004190 }
4191 } else {
4192 result = BAD_VALUE;
4193 }
4194 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4195 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004196
Mathias Agopian74c40c02010-09-29 13:02:36 -07004197 return result;
4198}
4199
Mathias Agopiand5556842013-09-19 17:08:37 -07004200void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004201 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004202 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004203 for (size_t y=0 ; y<h ; y++) {
4204 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4205 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004206 if (p[x] != 0xFF000000) return;
4207 }
4208 }
4209 ALOGE("*** we just took a black screenshot ***\n"
4210 "requested minz=%d, maxz=%d, layerStack=%d",
4211 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004212
Robert Carr2047fae2016-11-28 14:09:09 -08004213 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004214 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004215 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004216 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4217 state.z <= maxLayerZ) {
4218 layer->traverseInZOrder([&](Layer* layer) {
4219 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4220 layer->isVisible() ? '+' : '-',
4221 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004222 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004223 i++;
4224 });
4225 }
4226 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004227 }
4228}
4229
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004230// ---------------------------------------------------------------------------
4231
Robert Carr2047fae2016-11-28 14:09:09 -08004232void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
4233 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004234}
4235
Robert Carr2047fae2016-11-28 14:09:09 -08004236void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
4237 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004238}
4239
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004241
4242
4243#if defined(__gl_h_)
4244#error "don't include gl/gl.h in this file"
4245#endif
4246
4247#if defined(__gl2_h_)
4248#error "don't include gl2/gl2.h in this file"
4249#endif