blob: 8cc8e318a6cedc77a60e46c543c701fc954f51f1 [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 Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
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"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#define DISPLAY_COUNT 1
87
Mathias Agopianfee2b462013-07-03 12:34:01 -070088/*
89 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
90 * black pixels.
91 */
92#define DEBUG_SCREENSHOTS false
93
Mathias Agopianca088332013-03-28 17:44:13 -070094EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
95
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080096namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070097
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070098// This is the phase offset in nanoseconds of the software vsync event
99// relative to the vsync event reported by HWComposer. The software vsync
100// event is when SurfaceFlinger and Choreographer-based applications run each
101// frame.
102//
103// This phase offset allows adjustment of the minimum latency from application
104// wake-up (by Choregographer) time to the time at which the resulting window
105// image is displayed. This value may be either positive (after the HW vsync)
106// or negative (before the HW vsync). Setting it to 0 will result in a
107// minimum latency of two vsync periods because the app and SurfaceFlinger
108// will run just after the HW vsync. Setting it to a positive number will
109// result in the minimum latency being:
110//
111// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
112//
113// Note that reducing this latency makes it more likely for the applications
114// to not have their window content image ready in time. When this happens
115// the latency will end up being an additional vsync period, and animations
116// will hiccup. Therefore, this latency should be tuned somewhat
117// conservatively (or at least with awareness of the trade-off being made).
118static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
119
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700120// This is the phase offset at which SurfaceFlinger's composition runs.
121static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123// ---------------------------------------------------------------------------
124
Mathias Agopian99b49842011-06-27 16:05:52 -0700125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
131
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800132SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700133 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700135 mTransactionPending(false),
136 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700137 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700138 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700139 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700140 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800142 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800144 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800145 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800146 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700147 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700148 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700149 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700150 mDebugInSwapBuffers(0),
151 mLastSwapBufferTime(0),
152 mDebugInTransaction(0),
153 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700154 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700155 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700156 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000157 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700158 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700159 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800160 mHasColorMatrix(false),
161 mHasPoweredOff(false),
162 mFrameBuckets(),
163 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700164 mLastSwapTime(0),
165 mNumLayers(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800166{
Steve Blocka19954a2012-01-04 20:05:49 +0000167 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800168
169 // debugging stuff...
170 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700171
Mathias Agopianb4b17302013-03-20 18:36:41 -0700172 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700173 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175 property_get("debug.sf.showupdates", value, "0");
176 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700177
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700178 property_get("debug.sf.ddms", value, "0");
179 mDebugDDMS = atoi(value);
180 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700181 if (!startDdmConnection()) {
182 // start failed, and DDMS debugging not enabled
183 mDebugDDMS = 0;
184 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700185 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700186 ALOGI_IF(mDebugRegion, "showupdates enabled");
187 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700188
189 property_get("debug.sf.disable_backpressure", value, "0");
190 mPropagateBackpressure = !atoi(value);
191 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700192
193 property_get("debug.sf.disable_hwc_vds", value, "0");
194 mUseHwcVirtualDisplays = !atoi(value);
195 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800196
197 property_get("ro.sf.disable_triple_buffer", value, "0");
198 mLayerTripleBufferingDisabled = !atoi(value);
199 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800200}
201
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800202void SurfaceFlinger::onFirstRef()
203{
204 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205}
206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207SurfaceFlinger::~SurfaceFlinger()
208{
Mathias Agopiana4912602012-07-12 14:25:33 -0700209 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
210 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
211 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212}
213
Dan Stozac7014012014-02-14 15:03:43 -0800214void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800215{
216 // the window manager died on us. prepare its eulogy.
217
Andy McFadden13a082e2012-08-24 10:16:42 -0700218 // restore initial conditions (default device unblank, etc)
219 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220
221 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700222 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800223}
224
Robert Carr1db73f62016-12-21 12:58:51 -0800225static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700226 status_t err = client->initCheck();
227 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800228 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229 }
Robert Carr1db73f62016-12-21 12:58:51 -0800230 return nullptr;
231}
232
233sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
234 return initClient(new Client(this));
235}
236
237sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
238 const sp<IGraphicBufferProducer>& gbp) {
239 if (authenticateSurfaceTexture(gbp) == false) {
240 return nullptr;
241 }
242 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
243 if (layer == nullptr) {
244 return nullptr;
245 }
246
247 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800248}
249
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700250sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
251 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700252{
253 class DisplayToken : public BBinder {
254 sp<SurfaceFlinger> flinger;
255 virtual ~DisplayToken() {
256 // no more references, this display must be terminated
257 Mutex::Autolock _l(flinger->mStateLock);
258 flinger->mCurrentState.displays.removeItem(this);
259 flinger->setTransactionFlags(eDisplayTransactionNeeded);
260 }
261 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700262 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700263 : flinger(flinger) {
264 }
265 };
266
267 sp<BBinder> token = new DisplayToken(this);
268
269 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700270 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700271 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700272 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700273 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700274 return token;
275}
276
Jesse Hall6c913be2013-08-08 12:15:49 -0700277void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
278 Mutex::Autolock _l(mStateLock);
279
280 ssize_t idx = mCurrentState.displays.indexOfKey(display);
281 if (idx < 0) {
282 ALOGW("destroyDisplay: invalid display token");
283 return;
284 }
285
286 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
287 if (!info.isVirtualDisplay()) {
288 ALOGE("destroyDisplay called for non-virtual display");
289 return;
290 }
Irvelffc9efc2016-07-27 15:16:37 -0700291 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700292 mCurrentState.displays.removeItemsAt(idx);
293 setTransactionFlags(eDisplayTransactionNeeded);
294}
295
Jesse Hall692c7232012-11-08 15:41:56 -0800296void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800297 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800298 ALOGW_IF(mBuiltinDisplays[type],
299 "Overwriting display token for display type %d", type);
300 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800301 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700302 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800303 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700304 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800305}
306
Mathias Agopiane57f2922012-08-09 16:29:12 -0700307sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700308 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700309 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
310 return NULL;
311 }
Jesse Hall692c7232012-11-08 15:41:56 -0800312 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700313}
314
Jamie Gennis9a78c902011-01-12 18:30:40 -0800315sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
316{
317 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
318 return gba;
319}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321void SurfaceFlinger::bootFinished()
322{
323 const nsecs_t now = systemTime();
324 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000325 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700326 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700327
328 // wait patiently for the window manager death
329 const String16 name("window");
330 sp<IBinder> window(defaultServiceManager()->getService(name));
331 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700332 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700333 }
334
335 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700336 // formerly we would just kill the process, but we now ask it to exit so it
337 // can choose where to stop the animation.
338 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700339
340 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
341 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
342 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343}
344
Mathias Agopian3f844832013-08-07 21:24:32 -0700345void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700346 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700347 RenderEngine& engine;
348 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700349 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700350 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
351 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700352 }
353 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700354 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700355 return true;
356 }
357 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700358 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700359}
360
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361class DispSyncSource : public VSyncSource, private DispSync::Callback {
362public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700363 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000364 const char* name) :
365 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700366 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700367 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000368 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
369 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700370 mDispSync(dispSync),
371 mCallbackMutex(),
372 mCallback(),
373 mVsyncMutex(),
374 mPhaseOffset(phaseOffset),
375 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700376
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 virtual ~DispSyncSource() {}
378
379 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700380 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000382 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700383 static_cast<DispSync::Callback*>(this));
384 if (err != NO_ERROR) {
385 ALOGE("error registering vsync callback: %s (%d)",
386 strerror(-err), err);
387 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700388 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389 } else {
390 status_t err = mDispSync->removeEventListener(
391 static_cast<DispSync::Callback*>(this));
392 if (err != NO_ERROR) {
393 ALOGE("error unregistering vsync callback: %s (%d)",
394 strerror(-err), err);
395 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700397 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700399 }
400
401 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700402 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700403 mCallback = callback;
404 }
405
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700406 virtual void setPhaseOffset(nsecs_t phaseOffset) {
407 Mutex::Autolock lock(mVsyncMutex);
408
409 // Normalize phaseOffset to [0, period)
410 auto period = mDispSync->getPeriod();
411 phaseOffset %= period;
412 if (phaseOffset < 0) {
413 // If we're here, then phaseOffset is in (-period, 0). After this
414 // operation, it will be in (0, period)
415 phaseOffset += period;
416 }
417 mPhaseOffset = phaseOffset;
418
419 // If we're not enabled, we don't need to mess with the listeners
420 if (!mEnabled) {
421 return;
422 }
423
424 // Remove the listener with the old offset
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
431
432 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error registering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
439 }
440
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441private:
442 virtual void onDispSyncEvent(nsecs_t when) {
443 sp<VSyncSource::Callback> callback;
444 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 callback = mCallback;
447
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700448 if (mTraceVsync) {
449 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700450 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700451 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 }
453
454 if (callback != NULL) {
455 callback->onVSyncEvent(when);
456 }
457 }
458
Tim Murray4a4e4a22016-04-19 16:29:23 +0000459 const char* const mName;
460
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 int mValue;
462
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700463 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700464 const String8 mVsyncOnLabel;
465 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700466
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700467 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700468
469 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471
472 Mutex mVsyncMutex; // Protects the following
473 nsecs_t mPhaseOffset;
474 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700475};
476
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700477class InjectVSyncSource : public VSyncSource {
478public:
479 InjectVSyncSource() {}
480
481 virtual ~InjectVSyncSource() {}
482
483 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
484 std::lock_guard<std::mutex> lock(mCallbackMutex);
485 mCallback = callback;
486 }
487
488 virtual void onInjectSyncEvent(nsecs_t when) {
489 std::lock_guard<std::mutex> lock(mCallbackMutex);
490 mCallback->onVSyncEvent(when);
491 }
492
493 virtual void setVSyncEnabled(bool) {}
494 virtual void setPhaseOffset(nsecs_t) {}
495
496private:
497 std::mutex mCallbackMutex; // Protects the following
498 sp<VSyncSource::Callback> mCallback;
499};
500
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700502 ALOGI( "SurfaceFlinger's main thread ready to run. "
503 "Initializing graphics H/W...");
504
Dan Stoza9e56aa02015-11-02 13:00:03 -0800505 { // Autolock scope
506 Mutex::Autolock _l(mStateLock);
507
508 // initialize EGL for the default display
509 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
510 eglInitialize(mEGLDisplay, NULL, NULL);
511
512 // start the EventThread
513 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
514 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700515 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800516 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
517 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700518 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800519 mEventQueue.setEventThread(mSFEventThread);
520
Tim Murrayacff43d2016-07-29 13:57:24 -0700521 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700522 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700523 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700524 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
525 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
526 }
527
Dan Stoza9e56aa02015-11-02 13:00:03 -0800528 // Get a RenderEngine for the given display / config (can't fail)
529 mRenderEngine = RenderEngine::create(mEGLDisplay,
530 HAL_PIXEL_FORMAT_RGBA_8888);
531 }
532
533 // Drop the state lock while we initialize the hardware composer. We drop
534 // the lock because on creation, it will call back into SurfaceFlinger to
535 // initialize the primary display.
536 mHwc = new HWComposer(this);
537 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
538
Jesse Hall692c7232012-11-08 15:41:56 -0800539 Mutex::Autolock _l(mStateLock);
540
Mathias Agopian875d8e12013-06-07 15:35:48 -0700541 // retrieve the EGL context that was selected/created
542 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700543
Mathias Agopianda27af92012-09-13 18:17:13 -0700544 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
545 "couldn't create EGLContext");
546
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 // make the GLContext current so that we can create textures when creating
548 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700549 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
550
Jamie Gennisd1700752013-10-14 12:22:52 -0700551 mEventControlThread = new EventControlThread(this);
552 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
553
Mathias Agopian92a979a2012-08-02 18:32:23 -0700554 // initialize our drawing state
555 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700556
Andy McFadden13a082e2012-08-24 10:16:42 -0700557 // set initial conditions (e.g. unblank default device)
558 initializeDisplays();
559
Dan Stoza4e637772016-07-28 13:31:51 -0700560 mRenderEngine->primeCache();
561
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700562 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700566}
567
Mathias Agopiana67e4182012-06-19 17:26:12 -0700568void SurfaceFlinger::startBootAnim() {
569 // start boot animation
570 property_set("service.bootanim.exit", "0");
571 property_set("ctl.start", "bootanim");
572}
573
Mathias Agopian875d8e12013-06-07 15:35:48 -0700574size_t SurfaceFlinger::getMaxTextureSize() const {
575 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700576}
577
Mathias Agopian875d8e12013-06-07 15:35:48 -0700578size_t SurfaceFlinger::getMaxViewportDims() const {
579 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700580}
581
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800582// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800583
Jamie Gennis582270d2011-08-17 18:19:00 -0700584bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800585 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800586 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800587 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700588 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800589}
590
Brian Anderson069b3652016-07-22 10:32:47 -0700591status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700592 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700593 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700594 FrameEvent::REQUESTED_PRESENT,
595 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700596 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700597 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700598 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700599 FrameEvent::GL_COMPOSITION_DONE,
Brian Anderson3d4039d2016-09-23 16:31:30 -0700600 getHwComposer().presentFenceRepresentsStartOfScanout() ?
Brian Anderson3890c392016-07-25 12:48:08 -0700601 FrameEvent::DISPLAY_PRESENT : FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700602 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700603 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700604 };
605 return NO_ERROR;
606}
607
Dan Stoza7f7da322014-05-02 15:26:25 -0700608status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
609 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700610 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700611 return BAD_VALUE;
612 }
613
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500614 if (!display.get())
615 return NAME_NOT_FOUND;
616
Jesse Hall692c7232012-11-08 15:41:56 -0800617 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700618 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800619 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700620 type = i;
621 break;
622 }
623 }
624
625 if (type < 0) {
626 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700627 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700628
Mathias Agopian8b736f12012-08-13 17:54:26 -0700629 // TODO: Not sure if display density should handled by SF any longer
630 class Density {
631 static int getDensityFromProperty(char const* propName) {
632 char property[PROPERTY_VALUE_MAX];
633 int density = 0;
634 if (property_get(propName, property, NULL) > 0) {
635 density = atoi(property);
636 }
637 return density;
638 }
639 public:
640 static int getEmuDensity() {
641 return getDensityFromProperty("qemu.sf.lcd_density"); }
642 static int getBuildDensity() {
643 return getDensityFromProperty("ro.sf.lcd_density"); }
644 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700645
Dan Stoza7f7da322014-05-02 15:26:25 -0700646 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700647
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700649 DisplayInfo info = DisplayInfo();
650
Dan Stoza9e56aa02015-11-02 13:00:03 -0800651 float xdpi = hwConfig->getDpiX();
652 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700653
654 if (type == DisplayDevice::DISPLAY_PRIMARY) {
655 // The density of the device is provided by a build property
656 float density = Density::getBuildDensity() / 160.0f;
657 if (density == 0) {
658 // the build doesn't provide a density -- this is wrong!
659 // use xdpi instead
660 ALOGE("ro.sf.lcd_density must be defined as a build property");
661 density = xdpi / 160.0f;
662 }
663 if (Density::getEmuDensity()) {
664 // if "qemu.sf.lcd_density" is specified, it overrides everything
665 xdpi = ydpi = density = Density::getEmuDensity();
666 density /= 160.0f;
667 }
668 info.density = density;
669
670 // TODO: this needs to go away (currently needed only by webkit)
671 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
672 info.orientation = hw->getOrientation();
673 } else {
674 // TODO: where should this value come from?
675 static const int TV_DENSITY = 213;
676 info.density = TV_DENSITY / 160.0f;
677 info.orientation = 0;
678 }
679
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 info.w = hwConfig->getWidth();
681 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700682 info.xdpi = xdpi;
683 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800684 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700685 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686
Andy McFadden91b2ca82014-06-13 14:04:23 -0700687 // This is how far in advance a buffer must be queued for
688 // presentation at a given time. If you want a buffer to appear
689 // on the screen at time N, you must submit the buffer before
690 // (N - presentationDeadline).
691 //
692 // Normally it's one full refresh period (to give SF a chance to
693 // latch the buffer), but this can be reduced by configuring a
694 // DispSync offset. Any additional delays introduced by the hardware
695 // composer or panel must be accounted for here.
696 //
697 // We add an additional 1ms to allow for processing time and
698 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800699 info.presentationDeadline = hwConfig->getVsyncPeriod() -
700 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700701
702 // All non-virtual displays are currently considered secure.
703 info.secure = true;
704
Michael Wright28f24d02016-07-12 13:30:53 -0700705 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700706 }
707
Dan Stoza7f7da322014-05-02 15:26:25 -0700708 return NO_ERROR;
709}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700710
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800711status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700712 DisplayStatInfo* stats) {
713 if (stats == NULL) {
714 return BAD_VALUE;
715 }
716
717 // FIXME for now we always return stats for the primary display
718 memset(stats, 0, sizeof(*stats));
719 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
720 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
721 return NO_ERROR;
722}
723
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700724int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800725 if (display == NULL) {
726 ALOGE("%s : display is NULL", __func__);
727 return BAD_VALUE;
728 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700729 sp<DisplayDevice> device(getDisplayDevice(display));
730 if (device != NULL) {
731 return device->getActiveConfig();
732 }
733 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700734}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700735
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700736void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
737 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
738 this);
739 int32_t type = hw->getDisplayType();
740 int currentMode = hw->getActiveConfig();
741
742 if (mode == currentMode) {
743 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
744 return;
745 }
746
747 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
748 ALOGW("Trying to set config for virtual display");
749 return;
750 }
751
752 hw->setActiveConfig(mode);
753 getHwComposer().setActiveConfig(type, mode);
754}
755
756status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
757 class MessageSetActiveConfig: public MessageBase {
758 SurfaceFlinger& mFlinger;
759 sp<IBinder> mDisplay;
760 int mMode;
761 public:
762 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
763 int mode) :
764 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
765 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700766 Vector<DisplayInfo> configs;
767 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700768 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700769 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700770 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700771 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700772 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700773 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
774 if (hw == NULL) {
775 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700776 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700777 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
778 ALOGW("Attempt to set active config = %d for virtual display",
779 mMode);
780 } else {
781 mFlinger.setActiveConfigInternal(hw, mMode);
782 }
783 return true;
784 }
785 };
786 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
787 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700788 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700789}
Michael Wright28f24d02016-07-12 13:30:53 -0700790status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
791 Vector<android_color_mode_t>* outColorModes) {
792 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
793 return BAD_VALUE;
794 }
795
796 if (!display.get()) {
797 return NAME_NOT_FOUND;
798 }
799
800 int32_t type = NAME_NOT_FOUND;
801 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
802 if (display == mBuiltinDisplays[i]) {
803 type = i;
804 break;
805 }
806 }
807
808 if (type < 0) {
809 return type;
810 }
811
812 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
813 outColorModes->clear();
814 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
815
816 return NO_ERROR;
817}
818
819android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
820 sp<DisplayDevice> device(getDisplayDevice(display));
821 if (device != nullptr) {
822 return device->getActiveColorMode();
823 }
824 return static_cast<android_color_mode_t>(BAD_VALUE);
825}
826
827void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
828 android_color_mode_t mode) {
829 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
830 this);
831 int32_t type = hw->getDisplayType();
832 android_color_mode_t currentMode = hw->getActiveColorMode();
833
834 if (mode == currentMode) {
835 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
836 return;
837 }
838
839 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
840 ALOGW("Trying to set config for virtual display");
841 return;
842 }
843
844 hw->setActiveColorMode(mode);
845 getHwComposer().setActiveColorMode(type, mode);
846}
847
848
849status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
850 android_color_mode_t colorMode) {
851 class MessageSetActiveColorMode: public MessageBase {
852 SurfaceFlinger& mFlinger;
853 sp<IBinder> mDisplay;
854 android_color_mode_t mMode;
855 public:
856 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
857 android_color_mode_t mode) :
858 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
859 virtual bool handler() {
860 Vector<android_color_mode_t> modes;
861 mFlinger.getDisplayColorModes(mDisplay, &modes);
862 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
863 if (mMode < 0 || !exists) {
864 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
865 mDisplay.get());
866 return true;
867 }
868 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
869 if (hw == nullptr) {
870 ALOGE("Attempt to set active color mode = %d for null display %p",
871 mMode, mDisplay.get());
872 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
873 ALOGW("Attempt to set active color mode= %d for virtual display",
874 mMode);
875 } else {
876 mFlinger.setActiveColorModeInternal(hw, mMode);
877 }
878 return true;
879 }
880 };
881 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
882 postMessageSync(msg);
883 return NO_ERROR;
884}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700885
Svetoslavd85084b2014-03-20 10:28:31 -0700886status_t SurfaceFlinger::clearAnimationFrameStats() {
887 Mutex::Autolock _l(mStateLock);
888 mAnimFrameTracker.clearStats();
889 return NO_ERROR;
890}
891
892status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
893 Mutex::Autolock _l(mStateLock);
894 mAnimFrameTracker.getStats(outStats);
895 return NO_ERROR;
896}
897
Dan Stozac4f471e2016-03-24 09:31:08 -0700898status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
899 HdrCapabilities* outCapabilities) const {
900 Mutex::Autolock _l(mStateLock);
901
902 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
903 if (displayDevice == nullptr) {
904 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
905 return BAD_VALUE;
906 }
907
908 std::unique_ptr<HdrCapabilities> capabilities =
909 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
910 if (capabilities) {
911 std::swap(*outCapabilities, *capabilities);
912 } else {
913 return BAD_VALUE;
914 }
915
916 return NO_ERROR;
917}
918
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700919status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
920 if (enable == mInjectVSyncs) {
921 return NO_ERROR;
922 }
923
924 if (enable) {
925 mInjectVSyncs = enable;
926 ALOGV("VSync Injections enabled");
927 if (mVSyncInjector.get() == nullptr) {
928 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700929 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700930 }
931 mEventQueue.setEventThread(mInjectorEventThread);
932 } else {
933 mInjectVSyncs = enable;
934 ALOGV("VSync Injections disabled");
935 mEventQueue.setEventThread(mSFEventThread);
936 mVSyncInjector.clear();
937 }
938 return NO_ERROR;
939}
940
941status_t SurfaceFlinger::injectVSync(nsecs_t when) {
942 if (!mInjectVSyncs) {
943 ALOGE("VSync Injections not enabled");
944 return BAD_VALUE;
945 }
946 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
947 ALOGV("Injecting VSync inside SurfaceFlinger");
948 mVSyncInjector->onInjectSyncEvent(when);
949 }
950 return NO_ERROR;
951}
952
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800953// ----------------------------------------------------------------------------
954
955sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800956 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700957}
958
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800959// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800960
961void SurfaceFlinger::waitForEvent() {
962 mEventQueue.waitMessage();
963}
964
965void SurfaceFlinger::signalTransaction() {
966 mEventQueue.invalidate();
967}
968
969void SurfaceFlinger::signalLayerUpdate() {
970 mEventQueue.invalidate();
971}
972
973void SurfaceFlinger::signalRefresh() {
974 mEventQueue.refresh();
975}
976
977status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800978 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800979 return mEventQueue.postMessage(msg, reltime);
980}
981
982status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800983 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800984 status_t res = mEventQueue.postMessage(msg, reltime);
985 if (res == NO_ERROR) {
986 msg->wait();
987 }
988 return res;
989}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800990
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700991void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700992 do {
993 waitForEvent();
994 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800995}
996
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700997void SurfaceFlinger::enableHardwareVsync() {
998 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700999 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001000 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001001 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1002 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001003 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001004 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001005}
1006
Jesse Hall948fe0c2013-10-14 12:56:09 -07001007void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001008 Mutex::Autolock _l(mHWVsyncLock);
1009
Jesse Hall948fe0c2013-10-14 12:56:09 -07001010 if (makeAvailable) {
1011 mHWVsyncAvailable = true;
1012 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001013 // Hardware vsync is not currently available, so abort the resync
1014 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001015 return;
1016 }
1017
Dan Stoza9e56aa02015-11-02 13:00:03 -08001018 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1019 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001020
1021 mPrimaryDispSync.reset();
1022 mPrimaryDispSync.setPeriod(period);
1023
1024 if (!mPrimaryHWVsyncEnabled) {
1025 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001026 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1027 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001028 mPrimaryHWVsyncEnabled = true;
1029 }
1030}
1031
Jesse Hall948fe0c2013-10-14 12:56:09 -07001032void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001033 Mutex::Autolock _l(mHWVsyncLock);
1034 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001035 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1036 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001037 mPrimaryDispSync.endResync();
1038 mPrimaryHWVsyncEnabled = false;
1039 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001040 if (makeUnavailable) {
1041 mHWVsyncAvailable = false;
1042 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001043}
1044
Tim Murray4a4e4a22016-04-19 16:29:23 +00001045void SurfaceFlinger::resyncWithRateLimit() {
1046 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1047 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001048 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001049 }
1050}
1051
Dan Stoza9e56aa02015-11-02 13:00:03 -08001052void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001053 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001054
Jamie Gennisd1700752013-10-14 12:22:52 -07001055 { // Scope for the lock
1056 Mutex::Autolock _l(mHWVsyncLock);
1057 if (type == 0 && mPrimaryHWVsyncEnabled) {
1058 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001059 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001060 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001061
1062 if (needsHwVsync) {
1063 enableHardwareVsync();
1064 } else {
1065 disableHardwareVsync(false);
1066 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001067}
1068
Dan Stoza9e56aa02015-11-02 13:00:03 -08001069void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1070 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1071 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1072 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001073
Dan Stoza9e56aa02015-11-02 13:00:03 -08001074 // All non-virtual displays are currently considered secure.
1075 bool isSecure = true;
1076
1077 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1078 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1079 wp<IBinder> token = mBuiltinDisplays[type];
1080
1081 sp<IGraphicBufferProducer> producer;
1082 sp<IGraphicBufferConsumer> consumer;
1083 BufferQueue::createBufferQueue(&producer, &consumer,
1084 new GraphicBufferAlloc());
1085
1086 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1087 DisplayDevice::DISPLAY_PRIMARY, consumer);
1088 sp<DisplayDevice> hw = new DisplayDevice(this,
1089 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1090 producer, mRenderEngine->getEGLConfig());
1091 mDisplays.add(token, hw);
1092 } else {
1093 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001094 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001095 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001096 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001097 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001098 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1099 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001100 }
1101 setTransactionFlags(eDisplayTransactionNeeded);
1102
Andy McFadden9e9689c2012-10-10 18:17:51 -07001103 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001104 }
Mathias Agopian86303202012-07-24 22:46:10 -07001105}
1106
Dan Stoza9e56aa02015-11-02 13:00:03 -08001107void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001109 getHwComposer().setVsyncEnabled(disp,
1110 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001111}
1112
Mathias Agopian4fec8732012-06-29 14:12:52 -07001113void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001114 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001115 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001116 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001117 bool frameMissed = !mHadClientComposition &&
1118 mPreviousPresentFence != Fence::NO_FENCE &&
1119 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1120 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001121 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001122 signalLayerUpdate();
1123 break;
1124 }
1125
Dan Stoza6b9454d2014-11-07 16:00:59 -08001126 bool refreshNeeded = handleMessageTransaction();
1127 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001128 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001129 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001130 // Signal a refresh if a transaction modified the window state,
1131 // a new buffer was latched, or if HWC has requested a full
1132 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001133 signalRefresh();
1134 }
1135 break;
1136 }
1137 case MessageQueue::REFRESH: {
1138 handleMessageRefresh();
1139 break;
1140 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001141 }
1142}
1143
Dan Stoza6b9454d2014-11-07 16:00:59 -08001144bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001145 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001146 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001147 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001148 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001149 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001150 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001151}
1152
Dan Stoza6b9454d2014-11-07 16:00:59 -08001153bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001154 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001155 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001156}
1157
1158void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001159 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001160
Pablo Ceballos40845df2016-01-25 17:41:15 -08001161 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001162
Brian Andersond6927fb2016-07-23 23:37:30 -07001163 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001164 rebuildLayerStacks();
1165 setUpHWComposer();
1166 doDebugFlashRegions();
1167 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001168 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001169
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001170 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001171
1172 mHadClientComposition = false;
1173 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1174 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1175 mHadClientComposition = mHadClientComposition ||
1176 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1177 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001178
Dan Stoza9e56aa02015-11-02 13:00:03 -08001179 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001180}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001181
Mathias Agopiancd60f992012-08-16 16:28:27 -07001182void SurfaceFlinger::doDebugFlashRegions()
1183{
1184 // is debugging enabled
1185 if (CC_LIKELY(!mDebugRegion))
1186 return;
1187
1188 const bool repaintEverything = mRepaintEverything;
1189 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1190 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001191 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001192 // transform the dirty region into this screen's coordinate space
1193 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1194 if (!dirtyRegion.isEmpty()) {
1195 // redraw the whole screen
1196 doComposeSurfaces(hw, Region(hw->bounds()));
1197
1198 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001199 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001200 RenderEngine& engine(getRenderEngine());
1201 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1202
Mathias Agopianda27af92012-09-13 18:17:13 -07001203 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001204 }
1205 }
1206 }
1207
1208 postFramebuffer();
1209
1210 if (mDebugRegion > 1) {
1211 usleep(mDebugRegion * 1000);
1212 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001213
Dan Stoza9e56aa02015-11-02 13:00:03 -08001214 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001215 auto& displayDevice = mDisplays[displayId];
1216 if (!displayDevice->isDisplayOn()) {
1217 continue;
1218 }
1219
1220 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001221 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1222 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001223 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001224}
1225
Brian Andersond6927fb2016-07-23 23:37:30 -07001226void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001227{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 ATRACE_CALL();
1229 ALOGV("preComposition");
1230
Mathias Agopiancd60f992012-08-16 16:28:27 -07001231 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001232 mDrawingState.traverseInZOrder([&](Layer* layer) {
1233 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001234 needExtraInvalidate = true;
1235 }
Robert Carr2047fae2016-11-28 14:09:09 -08001236 });
1237
Mathias Agopiancd60f992012-08-16 16:28:27 -07001238 if (needExtraInvalidate) {
1239 signalLayerUpdate();
1240 }
1241}
1242
Brian Andersond6927fb2016-07-23 23:37:30 -07001243void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001244{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 ATRACE_CALL();
1246 ALOGV("postComposition");
1247
Brian Anderson3546a3f2016-07-14 11:51:14 -07001248 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001249 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001250 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001251 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001252 }
1253
Brian Andersond6927fb2016-07-23 23:37:30 -07001254 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001255
1256 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1257 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1258 glCompositionDoneFenceTime =
1259 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1260 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1261 } else {
1262 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1263 }
1264 mGlCompositionDoneTimeline.updateSignalTimes();
1265
1266 sp<Fence> displayFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1267 auto displayFenceTime = std::make_shared<FenceTime>(displayFence);
1268 mDisplayTimeline.push(displayFenceTime);
1269 mDisplayTimeline.updateSignalTimes();
1270
1271 const std::shared_ptr<FenceTime>* presentFenceTime = &FenceTime::NO_FENCE;
1272 const std::shared_ptr<FenceTime>* retireFenceTime = &FenceTime::NO_FENCE;
1273 if (mHwc->presentFenceRepresentsStartOfScanout()) {
1274 presentFenceTime = &displayFenceTime;
1275 } else {
1276 retireFenceTime = &displayFenceTime;
1277 }
Robert Carr2047fae2016-11-28 14:09:09 -08001278 mDrawingState.traverseInZOrder([&](Layer* layer) {
1279 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1280 *presentFenceTime, *retireFenceTime);
Dan Stozae77c7662016-05-13 11:37:28 -07001281 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001282 recordBufferingStats(layer->getName().string(),
1283 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001284 }
Robert Carr2047fae2016-11-28 14:09:09 -08001285 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001286
Brian Anderson3d4039d2016-09-23 16:31:30 -07001287 if (displayFence->isValid()) {
1288 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289 enableHardwareVsync();
1290 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001292 }
1293 }
1294
Andy McFadden5167ec62014-05-22 13:08:43 -07001295 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001296 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001297 enableHardwareVsync();
1298 }
1299 }
1300
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001301 if (mAnimCompositionPending) {
1302 mAnimCompositionPending = false;
1303
Brian Anderson3d4039d2016-09-23 16:31:30 -07001304 if (displayFenceTime->isValid()) {
1305 mAnimFrameTracker.setActualPresentFence(
1306 std::move(displayFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001307 } else {
1308 // The HWC doesn't support present fences, so use the refresh
1309 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001310 nsecs_t presentTime =
1311 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001312 mAnimFrameTracker.setActualPresentTime(presentTime);
1313 }
1314 mAnimFrameTracker.advanceFrame();
1315 }
Dan Stozab90cf072015-03-05 11:05:59 -08001316
1317 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1318 return;
1319 }
1320
1321 nsecs_t currentTime = systemTime();
1322 if (mHasPoweredOff) {
1323 mHasPoweredOff = false;
1324 } else {
1325 nsecs_t period = mPrimaryDispSync.getPeriod();
1326 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1327 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1328 if (numPeriods < NUM_BUCKETS - 1) {
1329 mFrameBuckets[numPeriods] += elapsedTime;
1330 } else {
1331 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1332 }
1333 mTotalTime += elapsedTime;
1334 }
1335 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001336}
1337
1338void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001339 ATRACE_CALL();
1340 ALOGV("rebuildLayerStacks");
1341
Mathias Agopiancd60f992012-08-16 16:28:27 -07001342 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001343 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001344 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001345 mVisibleRegionsDirty = false;
1346 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001347
Mathias Agopian92a979a2012-08-02 18:32:23 -07001348 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001349 Region opaqueRegion;
1350 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001351 Vector<sp<Layer>> layersSortedByZ;
1352 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1353 const Transform& tr(displayDevice->getTransform());
1354 const Rect bounds(displayDevice->getBounds());
1355 if (displayDevice->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001356 computeVisibleRegions(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001357 displayDevice->getLayerStack(), dirtyRegion,
1358 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001359
Robert Carr2047fae2016-11-28 14:09:09 -08001360 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001361 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001362 Region drawRegion(tr.transform(
1363 layer->visibleNonTransparentRegion));
1364 drawRegion.andSelf(bounds);
1365 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001366 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001367 } else {
1368 // Clear out the HWC layer if this layer was
1369 // previously visible, but no longer is
1370 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1371 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001372 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001373 }
Robert Carr2047fae2016-11-28 14:09:09 -08001374 });
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001375 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001376 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1377 displayDevice->undefinedRegion.set(bounds);
1378 displayDevice->undefinedRegion.subtractSelf(
1379 tr.transform(opaqueRegion));
1380 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001381 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001382 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001383}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001384
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 ATRACE_CALL();
1387 ALOGV("setUpHWComposer");
1388
Jesse Hall028dc8f2013-08-20 16:35:32 -07001389 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001390 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1391 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1392 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1393
1394 // If nothing has changed (!dirty), don't recompose.
1395 // If something changed, but we don't currently have any visible layers,
1396 // and didn't when we last did a composition, then skip it this time.
1397 // The second rule does two things:
1398 // - When all layers are removed from a display, we'll emit one black
1399 // frame, then nothing more until we get new layers.
1400 // - When a display is created with a private layer stack, we won't
1401 // emit any black frames until a layer is added to the layer stack.
1402 bool mustRecompose = dirty && !(empty && wasEmpty);
1403
1404 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1405 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1406 mustRecompose ? "doing" : "skipping",
1407 dirty ? "+" : "-",
1408 empty ? "+" : "-",
1409 wasEmpty ? "+" : "-");
1410
Dan Stoza71433162014-02-04 16:22:36 -08001411 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001412
1413 if (mustRecompose) {
1414 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1415 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001416 }
1417
Dan Stoza9e56aa02015-11-02 13:00:03 -08001418 // build the h/w work list
1419 if (CC_UNLIKELY(mGeometryInvalid)) {
1420 mGeometryInvalid = false;
1421 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1422 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1423 const auto hwcId = displayDevice->getHwcDisplayId();
1424 if (hwcId >= 0) {
1425 const Vector<sp<Layer>>& currentLayers(
1426 displayDevice->getVisibleLayersSortedByZ());
1427 bool foundLayerWithoutHwc = false;
Robert Carrae060832016-11-28 10:51:00 -08001428 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001429 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 if (!layer->hasHwcLayer(hwcId)) {
1431 auto hwcLayer = mHwc->createLayer(hwcId);
1432 if (hwcLayer) {
1433 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1434 } else {
1435 layer->forceClientComposition(hwcId);
1436 foundLayerWithoutHwc = true;
1437 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001438 }
1439 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001440
Robert Carrae060832016-11-28 10:51:00 -08001441 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001442 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001443 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001444 }
1445 }
1446 }
1447 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001448 }
Riley Andrews03414a12014-07-01 14:22:59 -07001449
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001450
1451 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1452
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 // Set the per-frame data
1454 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1455 auto& displayDevice = mDisplays[displayId];
1456 const auto hwcId = displayDevice->getHwcDisplayId();
1457 if (hwcId < 0) {
1458 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001459 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001460 if (colorMatrix != mPreviousColorMatrix) {
1461 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1462 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1463 "display %zd: %d", displayId, result);
1464 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1466 layer->setPerFrameData(displayDevice);
1467 }
1468 }
1469
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001470 mPreviousColorMatrix = colorMatrix;
1471
Dan Stoza9e56aa02015-11-02 13:00:03 -08001472 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001473 auto& displayDevice = mDisplays[displayId];
1474 if (!displayDevice->isDisplayOn()) {
1475 continue;
1476 }
1477
1478 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001479 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1480 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001481 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001482}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001483
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484void SurfaceFlinger::doComposition() {
1485 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001486 ALOGV("doComposition");
1487
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001488 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001489 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001490 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001491 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001492 // transform the dirty region into this screen's coordinate space
1493 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001494
1495 // repaint the framebuffer (if needed)
1496 doDisplayComposition(hw, dirtyRegion);
1497
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498 hw->dirtyRegion.clear();
1499 hw->flip(hw->swapRegion);
1500 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001501 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001502 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001503 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504}
1505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506void SurfaceFlinger::postFramebuffer()
1507{
Mathias Agopian841cde52012-03-01 15:44:37 -08001508 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001509 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001510
Mathias Agopiana44b0412011-10-16 18:46:35 -07001511 const nsecs_t now = systemTime();
1512 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001513
Dan Stoza9e56aa02015-11-02 13:00:03 -08001514 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1515 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001516 if (!displayDevice->isDisplayOn()) {
1517 continue;
1518 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001519 const auto hwcId = displayDevice->getHwcDisplayId();
1520 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001521 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001522 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001523 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001524 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1526 sp<Fence> releaseFence = Fence::NO_FENCE;
1527 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1528 releaseFence = displayDevice->getClientTargetAcquireFence();
1529 } else {
1530 auto hwcLayer = layer->getHwcLayer(hwcId);
1531 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001532 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 layer->onLayerDisplayed(releaseFence);
1534 }
1535 if (hwcId >= 0) {
1536 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001537 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001538 }
1539
Mathias Agopiana44b0412011-10-16 18:46:35 -07001540 mLastSwapBufferTime = systemTime() - now;
1541 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001542
1543 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1544 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1545 logFrameStats();
1546 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547}
1548
Mathias Agopian87baae12012-07-31 12:38:26 -07001549void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001550{
Mathias Agopian841cde52012-03-01 15:44:37 -08001551 ATRACE_CALL();
1552
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001553 // here we keep a copy of the drawing state (that is the state that's
1554 // going to be overwritten by handleTransactionLocked()) outside of
1555 // mStateLock so that the side-effects of the State assignment
1556 // don't happen with mStateLock held (which can cause deadlocks).
1557 State drawingState(mDrawingState);
1558
Mathias Agopianca4d3602011-05-19 15:38:14 -07001559 Mutex::Autolock _l(mStateLock);
1560 const nsecs_t now = systemTime();
1561 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562
Mathias Agopianca4d3602011-05-19 15:38:14 -07001563 // Here we're guaranteed that some transaction flags are set
1564 // so we can call handleTransactionLocked() unconditionally.
1565 // We call getTransactionFlags(), which will also clear the flags,
1566 // with mStateLock held to guarantee that mCurrentState won't change
1567 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001568
Mathias Agopiane57f2922012-08-09 16:29:12 -07001569 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001570 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001571
Mathias Agopianca4d3602011-05-19 15:38:14 -07001572 mLastTransactionTime = systemTime() - now;
1573 mDebugInTransaction = 0;
1574 invalidateHwcGeometry();
1575 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001576}
1577
Mathias Agopian87baae12012-07-31 12:38:26 -07001578void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001579{
Dan Stoza7dde5992015-05-22 09:51:44 -07001580 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001581 mCurrentState.traverseInZOrder([](Layer* layer) {
1582 layer->notifyAvailableFrames();
1583 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001584
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001585 /*
1586 * Traversal of the children
1587 * (perform the transaction for each of them if needed)
1588 */
1589
Mathias Agopian3559b072012-08-15 13:46:03 -07001590 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001591 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001592 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001593 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001594
1595 const uint32_t flags = layer->doTransaction(0);
1596 if (flags & Layer::eVisibleRegion)
1597 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001598 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001599 }
1600
1601 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001602 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001603 */
1604
Mathias Agopiane57f2922012-08-09 16:29:12 -07001605 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001606 // here we take advantage of Vector's copy-on-write semantics to
1607 // improve performance by skipping the transaction entirely when
1608 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001609 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1610 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001611 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001612 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001613 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001614 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001615
1616 // find the displays that were removed
1617 // (ie: in drawing state but not in current state)
1618 // also handle displays that changed
1619 // (ie: displays that are in both lists)
1620 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001621 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1622 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001623 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001624 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001625 // Call makeCurrent() on the primary display so we can
1626 // be sure that nothing associated with this display
1627 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001628 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001629 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001630 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1631 if (hw != NULL)
1632 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001633 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001634 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001635 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001636 } else {
1637 ALOGW("trying to remove the main display");
1638 }
1639 } else {
1640 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001641 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001642 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001643 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1644 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001645 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001646 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001647 // recreating the DisplayDevice, so we just remove it
1648 // from the drawing state, so that it get re-added
1649 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001650 sp<DisplayDevice> hw(getDisplayDevice(display));
1651 if (hw != NULL)
1652 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001653 mDisplays.removeItem(display);
1654 mDrawingState.displays.removeItemsAt(i);
1655 dc--; i--;
1656 // at this point we must loop to the next item
1657 continue;
1658 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001659
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001660 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001661 if (disp != NULL) {
1662 if (state.layerStack != draw[i].layerStack) {
1663 disp->setLayerStack(state.layerStack);
1664 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001665 if ((state.orientation != draw[i].orientation)
1666 || (state.viewport != draw[i].viewport)
1667 || (state.frame != draw[i].frame))
1668 {
1669 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001670 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001671 }
Michael Lentine47e45402014-07-18 15:34:25 -07001672 if (state.width != draw[i].width || state.height != draw[i].height) {
1673 disp->setDisplaySize(state.width, state.height);
1674 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001675 }
1676 }
1677 }
1678
1679 // find displays that were added
1680 // (ie: in current state but not in drawing state)
1681 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001682 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001683 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001684
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001685 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001686 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001687 sp<IGraphicBufferProducer> bqProducer;
1688 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001689 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1690 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001691
Dan Stoza9e56aa02015-11-02 13:00:03 -08001692 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001693 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001694 // Virtual displays without a surface are dormant:
1695 // they have external state (layer stack, projection,
1696 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001697 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001698
Dan Stoza8cf150a2016-08-02 10:27:31 -07001699 if (mUseHwcVirtualDisplays) {
1700 int width = 0;
1701 int status = state.surface->query(
1702 NATIVE_WINDOW_WIDTH, &width);
1703 ALOGE_IF(status != NO_ERROR,
1704 "Unable to query width (%d)", status);
1705 int height = 0;
1706 status = state.surface->query(
1707 NATIVE_WINDOW_HEIGHT, &height);
1708 ALOGE_IF(status != NO_ERROR,
1709 "Unable to query height (%d)", status);
1710 int intFormat = 0;
1711 status = state.surface->query(
1712 NATIVE_WINDOW_FORMAT, &intFormat);
1713 ALOGE_IF(status != NO_ERROR,
1714 "Unable to query format (%d)", status);
1715 auto format = static_cast<android_pixel_format_t>(
1716 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001717
Dan Stoza8cf150a2016-08-02 10:27:31 -07001718 mHwc->allocateVirtualDisplay(width, height, &format,
1719 &hwcId);
1720 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001721
Dan Stoza5cf424b2016-05-20 14:02:39 -07001722 // TODO: Plumb requested format back up to consumer
1723
Dan Stoza9e56aa02015-11-02 13:00:03 -08001724 sp<VirtualDisplaySurface> vds =
1725 new VirtualDisplaySurface(*mHwc,
1726 hwcId, state.surface, bqProducer,
1727 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001728
1729 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001730 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001731 }
1732 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001733 ALOGE_IF(state.surface!=NULL,
1734 "adding a supported display, but rendering "
1735 "surface is provided (%p), ignoring it",
1736 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1738 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1739 dispSurface = new FramebufferSurface(*mHwc,
1740 DisplayDevice::DISPLAY_EXTERNAL,
1741 bqConsumer);
1742 producer = bqProducer;
1743 } else {
1744 ALOGE("Attempted to add non-external non-virtual"
1745 " display");
1746 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001747 }
1748
1749 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001750 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001751 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 state.type, hwcId, state.isSecure, display,
1753 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001754 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001755 hw->setLayerStack(state.layerStack);
1756 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001757 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001758 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001759 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001760 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001761 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001762 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001763 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001764 }
1765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001766 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001767 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001768
Mathias Agopian84300952012-11-21 16:02:13 -08001769 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1770 // The transform hint might have changed for some layers
1771 // (either because a display has changed, or because a layer
1772 // as changed).
1773 //
1774 // Walk through all the layers in currentLayers,
1775 // and update their transform hint.
1776 //
1777 // If a layer is visible only on a single display, then that
1778 // display is used to calculate the hint, otherwise we use the
1779 // default display.
1780 //
1781 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1782 // the hint is set before we acquire a buffer from the surface texture.
1783 //
1784 // NOTE: layer transactions have taken place already, so we use their
1785 // drawing state. However, SurfaceFlinger's own transaction has not
1786 // happened yet, so we must use the current state layer list
1787 // (soon to become the drawing state list).
1788 //
1789 sp<const DisplayDevice> disp;
1790 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001791 bool first = true;
1792 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08001793 // NOTE: we rely on the fact that layers are sorted by
1794 // layerStack first (so we don't have to traverse the list
1795 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001797 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08001798 currentlayerStack = layerStack;
1799 // figure out if this layerstack is mirrored
1800 // (more than one display) if so, pick the default display,
1801 // if not, pick the only display it's on.
1802 disp.clear();
1803 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1804 sp<const DisplayDevice> hw(mDisplays[dpy]);
1805 if (hw->getLayerStack() == currentlayerStack) {
1806 if (disp == NULL) {
1807 disp = hw;
1808 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001809 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001810 break;
1811 }
1812 }
1813 }
1814 }
Chet Haase91d25932013-04-11 15:24:55 -07001815 if (disp == NULL) {
1816 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1817 // redraw after transform hint changes. See bug 8508397.
1818
1819 // could be null when this layer is using a layerStack
1820 // that is not visible on any display. Also can occur at
1821 // screen off/on times.
1822 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001823 }
Chet Haase91d25932013-04-11 15:24:55 -07001824 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001825
1826 first = false;
1827 });
Mathias Agopian84300952012-11-21 16:02:13 -08001828 }
1829
1830
Mathias Agopian3559b072012-08-15 13:46:03 -07001831 /*
1832 * Perform our own transaction if needed
1833 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001834
1835 if (mLayersAdded) {
1836 mLayersAdded = false;
1837 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07001838 mVisibleRegionsDirty = true;
1839 }
1840
1841 // some layers might have been removed, so
1842 // we need to update the regions they're exposing.
1843 if (mLayersRemoved) {
1844 mLayersRemoved = false;
1845 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001846 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001847 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001848 // this layer is not visible anymore
1849 // TODO: we could traverse the tree from front to back and
1850 // compute the actual visible region
1851 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001852 Region visibleReg;
1853 visibleReg.set(layer->computeScreenBounds());
1854 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001855 }
Robert Carr2047fae2016-11-28 14:09:09 -08001856 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001857 }
1858
1859 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001860
1861 updateCursorAsync();
1862}
1863
1864void SurfaceFlinger::updateCursorAsync()
1865{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1867 auto& displayDevice = mDisplays[displayId];
1868 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001869 continue;
1870 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871
1872 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1873 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001874 }
1875 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001876}
1877
1878void SurfaceFlinger::commitTransaction()
1879{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001880 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001881 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 for (const auto& l : mLayersPendingRemoval) {
1883 recordBufferingStats(l->getName().string(),
1884 l->getOccupancyHistory(true));
1885 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001886 }
1887 mLayersPendingRemoval.clear();
1888 }
1889
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001890 // If this transaction is part of a window animation then the next frame
1891 // we composite should be considered an animation as well.
1892 mAnimCompositionPending = mAnimTransactionPending;
1893
Mathias Agopian4fec8732012-06-29 14:12:52 -07001894 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001895 mDrawingState.traverseInZOrder([](Layer* layer) {
1896 layer->commitChildList();
1897 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001898 mTransactionPending = false;
1899 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001900 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001901}
1902
Robert Carr2047fae2016-11-28 14:09:09 -08001903void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07001904 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001905{
Mathias Agopian841cde52012-03-01 15:44:37 -08001906 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001908
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001909 Region aboveOpaqueLayers;
1910 Region aboveCoveredLayers;
1911 Region dirty;
1912
Mathias Agopian87baae12012-07-31 12:38:26 -07001913 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001914
Robert Carr2047fae2016-11-28 14:09:09 -08001915 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001916 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001917 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918
Jesse Hall01e29052013-02-19 16:13:35 -08001919 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001920 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001921 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07001922
Mathias Agopianab028732010-03-16 16:41:46 -07001923 /*
1924 * opaqueRegion: area of a surface that is fully opaque.
1925 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001927
1928 /*
1929 * visibleRegion: area of a surface that is visible on screen
1930 * and not fully transparent. This is essentially the layer's
1931 * footprint minus the opaque regions above it.
1932 * Areas covered by a translucent surface are considered visible.
1933 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001935
1936 /*
1937 * coveredRegion: area of a surface that is covered by all
1938 * visible regions above it (which includes the translucent areas).
1939 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001940 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001941
Jesse Halla8026d22012-09-25 13:25:04 -07001942 /*
1943 * transparentRegion: area of a surface that is hinted to be completely
1944 * transparent. This is only used to tell when the layer has no visible
1945 * non-transparent regions and can be removed from the layer list. It
1946 * does not affect the visibleRegion of this layer or any layers
1947 * beneath it. The hint may not be correct if apps don't respect the
1948 * SurfaceView restrictions (which, sadly, some don't).
1949 */
1950 Region transparentRegion;
1951
Mathias Agopianab028732010-03-16 16:41:46 -07001952
1953 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001954 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001955 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001956 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001957 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001958 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07001959 if (!visibleRegion.isEmpty()) {
1960 // Remove the transparent area from the visible region
1961 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001962 if (tr.preserveRects()) {
1963 // transform the transparent region
1964 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001965 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001966 // transformation too complex, can't do the
1967 // transparent region optimization.
1968 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001969 }
Mathias Agopianab028732010-03-16 16:41:46 -07001970 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971
Mathias Agopianab028732010-03-16 16:41:46 -07001972 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001973 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001975 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1976 // the opaque region is the layer's footprint
1977 opaqueRegion = visibleRegion;
1978 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001979 }
1980 }
1981
Mathias Agopianab028732010-03-16 16:41:46 -07001982 // Clip the covered region to the visible region
1983 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1984
1985 // Update aboveCoveredLayers for next (lower) layer
1986 aboveCoveredLayers.orSelf(visibleRegion);
1987
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 // subtract the opaque region covered by the layers above us
1989 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990
1991 // compute this layer's dirty region
1992 if (layer->contentDirty) {
1993 // we need to invalidate the whole region
1994 dirty = visibleRegion;
1995 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001996 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997 layer->contentDirty = false;
1998 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001999 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002000 * the exposed region consists of two components:
2001 * 1) what's VISIBLE now and was COVERED before
2002 * 2) what's EXPOSED now less what was EXPOSED before
2003 *
2004 * note that (1) is conservative, we start with the whole
2005 * visible region but only keep what used to be covered by
2006 * something -- which mean it may have been exposed.
2007 *
2008 * (2) handles areas that were not covered by anything but got
2009 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002010 */
Mathias Agopianab028732010-03-16 16:41:46 -07002011 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012 const Region oldVisibleRegion = layer->visibleRegion;
2013 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002014 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2015 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016 }
2017 dirty.subtractSelf(aboveOpaqueLayers);
2018
2019 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002020 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002021
Mathias Agopianab028732010-03-16 16:41:46 -07002022 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002024
Jesse Halla8026d22012-09-25 13:25:04 -07002025 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002026 layer->setVisibleRegion(visibleRegion);
2027 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002028 layer->setVisibleNonTransparentRegion(
2029 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002030 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031
Mathias Agopian87baae12012-07-31 12:38:26 -07002032 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033}
2034
Mathias Agopian87baae12012-07-31 12:38:26 -07002035void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2036 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002037 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002038 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2039 if (hw->getLayerStack() == layerStack) {
2040 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002041 }
2042 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002043}
2044
Dan Stoza6b9454d2014-11-07 16:00:59 -08002045bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047 ALOGV("handlePageFlip");
2048
Brian Andersond6927fb2016-07-23 23:37:30 -07002049 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050
Mathias Agopian4fec8732012-06-29 14:12:52 -07002051 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002052 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002053
2054 // Store the set of layers that need updates. This set must not change as
2055 // buffers are being latched, as this could result in a deadlock.
2056 // Example: Two producers share the same command stream and:
2057 // 1.) Layer 0 is latched
2058 // 2.) Layer 0 gets a new frame
2059 // 2.) Layer 1 gets a new frame
2060 // 3.) Layer 1 is latched.
2061 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2062 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002063 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002064 if (layer->hasQueuedFrame()) {
2065 frameQueued = true;
2066 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002067 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002068 } else {
2069 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002070 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002071 } else {
2072 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002073 }
Robert Carr2047fae2016-11-28 14:09:09 -08002074 });
2075
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002077 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002078 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002079 invalidateLayerStack(layer->getLayerStack(), dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002080 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002081
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002082 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002083
2084 // If we will need to wake up at some time in the future to deal with a
2085 // queued frame that shouldn't be displayed during this vsync period, wake
2086 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002088 signalLayerUpdate();
2089 }
2090
2091 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002093}
2094
Mathias Agopianad456f92011-01-13 17:53:01 -08002095void SurfaceFlinger::invalidateHwcGeometry()
2096{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002098}
2099
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002100
Fabien Sanglard830b8472016-11-30 16:35:58 -08002101void SurfaceFlinger::doDisplayComposition(
2102 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002103 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104{
Dan Stoza71433162014-02-04 16:22:36 -08002105 // We only need to actually compose the display if:
2106 // 1) It is being handled by hardware composer, which may need this to
2107 // keep its virtual display state machine in sync, or
2108 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002109 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002110 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002112 return;
2113 }
2114
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 ALOGV("doDisplayComposition");
2116
Mathias Agopian87baae12012-07-31 12:38:26 -07002117 Region dirtyRegion(inDirtyRegion);
2118
Mathias Agopianb8a55602009-06-26 19:06:36 -07002119 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002120 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121
Fabien Sanglard830b8472016-11-30 16:35:58 -08002122 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002123 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002124 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2125 // takes a rectangle, we must make sure to update that whole
2126 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002127 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002128 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002129 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002130 // We need to redraw the rectangle that will be updated
2131 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002132 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002133 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002134 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002135 } else {
2136 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002137 dirtyRegion.set(displayDevice->bounds());
2138 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139 }
2140 }
2141
Fabien Sanglard830b8472016-11-30 16:35:58 -08002142 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002143
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002144 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002145 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002146
2147 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002148 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002149}
2150
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151bool SurfaceFlinger::doComposeSurfaces(
2152 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002153{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002155
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002157
2158 mat4 oldColorMatrix;
2159 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2160 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2161 if (applyColorMatrix) {
2162 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2163 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2164 }
2165
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2167 if (hasClientComposition) {
2168 ALOGV("hasClientComposition");
2169
2170 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002171 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002173 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2174 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2175 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2176 }
2177 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002178 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002179
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002180 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002181 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2182 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002183 // when using overlays, we assume a fully transparent framebuffer
2184 // NOTE: we could reduce how much we need to clear, for instance
2185 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002186 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002187 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002188 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002189 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002190 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002192
2193 // we remove the scissor part
2194 // we're left with the letterbox region
2195 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002196 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002197
2198 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002200
2201 // but limit it to the dirty region
2202 region.andSelf(dirty);
2203
Mathias Agopianb9494d52012-04-18 02:28:45 -07002204 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002205 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002206 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002208 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002209 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002210
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002212 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002213 // scissor on the main display. It should never be needed
2214 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 const Rect& bounds(displayDevice->getBounds());
2216 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002217 if (scissor != bounds) {
2218 // scissor doesn't match the screen's dimensions, so we
2219 // need to clear everything outside of it and enable
2220 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002221
Mathias Agopianf45c5102012-10-24 16:29:17 -07002222 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002223 const uint32_t height = displayDevice->getHeight();
2224 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002225 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002226 }
2227 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002228 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002229
Mathias Agopian85d751c2012-08-29 16:59:24 -07002230 /*
2231 * and then, render the layers targeted at the framebuffer
2232 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002233
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 ALOGV("Rendering client layers");
2235 const Transform& displayTransform = displayDevice->getTransform();
2236 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002237 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002238 bool firstLayer = true;
2239 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2240 const Region clip(dirty.intersect(
2241 displayTransform.transform(layer->visibleRegion)));
2242 ALOGV("Layer: %s", layer->getName().string());
2243 ALOGV(" Composition type: %s",
2244 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002245 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 switch (layer->getCompositionType(hwcId)) {
2247 case HWC2::Composition::Cursor:
2248 case HWC2::Composition::Device:
2249 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002250 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002251 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2252 layer->isOpaque(state) && (state.alpha == 1.0f)
2253 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002254 // never clear the very first layer since we're
2255 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002256 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002257 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002258 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002259 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002260 case HWC2::Composition::Client: {
2261 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002262 break;
2263 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002264 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002265 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002266 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 } else {
2268 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002269 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002271 }
2272 } else {
2273 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002274 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002275 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002276 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002277 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002279 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002280 }
2281 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002282
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002283 if (applyColorMatrix) {
2284 getRenderEngine().setupColorTransform(oldColorMatrix);
2285 }
2286
Mathias Agopianf45c5102012-10-24 16:29:17 -07002287 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002288 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002289 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290}
2291
Fabien Sanglard830b8472016-11-30 16:35:58 -08002292void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2293 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002294 RenderEngine& engine(getRenderEngine());
2295 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Dan Stoza7d89d062015-04-30 13:29:25 -07002298status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002299 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002300 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 const sp<Layer>& lbc,
2302 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002303{
Dan Stoza7d89d062015-04-30 13:29:25 -07002304 // add this layer to the current state list
2305 {
2306 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002307 if (mNumLayers >= MAX_LAYERS) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002308 return NO_MEMORY;
2309 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002310 if (parent == nullptr) {
2311 mCurrentState.layersSortedByZ.add(lbc);
2312 } else {
2313 parent->addChild(lbc);
2314 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002315 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002316 mLayersAdded = true;
2317 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002318 }
2319
Mathias Agopian96f08192010-06-02 23:28:45 -07002320 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002321 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002322
Dan Stoza7d89d062015-04-30 13:29:25 -07002323 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002324}
2325
Dan Stoza22851c32016-08-09 13:21:03 -07002326status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002328 sp<Layer> layer = weakLayer.promote();
2329 if (layer == nullptr) {
2330 // The layer has already been removed, carry on
2331 return NO_ERROR;
2332 }
2333
Robert Carr1f0a16a2016-10-24 16:27:39 -07002334 const auto& p = layer->getParent();
2335 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2336 mCurrentState.layersSortedByZ.remove(layer);
2337
2338 if (index < 0) {
2339 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2340 layer->getName().string(),
2341 (p != nullptr) ? p->getName().string() : "no-parent");
2342 return BAD_VALUE;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002343 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002344
2345 mLayersPendingRemoval.add(layer);
2346 mLayersRemoved = true;
2347 mNumLayers--;
2348 setTransactionFlags(eTransactionNeeded);
2349 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350}
2351
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002352uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002353 return android_atomic_release_load(&mTransactionFlags);
2354}
2355
Mathias Agopian3f844832013-08-07 21:24:32 -07002356uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2358}
2359
Mathias Agopian3f844832013-08-07 21:24:32 -07002360uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2362 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002363 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 }
2365 return old;
2366}
2367
Mathias Agopian8b33f032012-07-24 20:43:54 -07002368void SurfaceFlinger::setTransactionState(
2369 const Vector<ComposerState>& state,
2370 const Vector<DisplayState>& displays,
2371 uint32_t flags)
2372{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002373 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002374 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002375 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002376
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002377 if (flags & eAnimation) {
2378 // For window updates that are part of an animation we must wait for
2379 // previous animation "frames" to be handled.
2380 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002381 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002382 if (CC_UNLIKELY(err != NO_ERROR)) {
2383 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002384 // caller after a few seconds.
2385 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2386 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002387 mAnimTransactionPending = false;
2388 break;
2389 }
2390 }
2391 }
2392
Mathias Agopiane57f2922012-08-09 16:29:12 -07002393 size_t count = displays.size();
2394 for (size_t i=0 ; i<count ; i++) {
2395 const DisplayState& s(displays[i]);
2396 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002397 }
2398
Mathias Agopiane57f2922012-08-09 16:29:12 -07002399 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002400 for (size_t i=0 ; i<count ; i++) {
2401 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002402 // Here we need to check that the interface we're given is indeed
2403 // one of our own. A malicious client could give us a NULL
2404 // IInterface, or one of its own or even one of our own but a
2405 // different type. All these situations would cause us to crash.
2406 //
2407 // NOTE: it would be better to use RTTI as we could directly check
2408 // that we have a Client*. however, RTTI is disabled in Android.
2409 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002410 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002411 if (binder != NULL) {
2412 String16 desc(binder->getInterfaceDescriptor());
2413 if (desc == ISurfaceComposerClient::descriptor) {
2414 sp<Client> client( static_cast<Client *>(s.client.get()) );
2415 transactionFlags |= setClientStateLocked(client, s.state);
2416 }
2417 }
2418 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002419 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002420
Robert Carr2a7dbb42016-05-24 11:41:28 -07002421 // If a synchronous transaction is explicitly requested without any changes,
2422 // force a transaction anyway. This can be used as a flush mechanism for
2423 // previous async transactions.
2424 if (transactionFlags == 0 && (flags & eSynchronous)) {
2425 transactionFlags = eTransactionNeeded;
2426 }
2427
Mathias Agopian386aa982011-11-07 21:58:03 -08002428 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002429 if (mInterceptor.isEnabled()) {
2430 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2431 }
Irvel468051e2016-06-13 16:44:44 -07002432
Mathias Agopian386aa982011-11-07 21:58:03 -08002433 // this triggers the transaction
2434 setTransactionFlags(transactionFlags);
2435
2436 // if this is a synchronous transaction, wait for it to take effect
2437 // before returning.
2438 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002439 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002440 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002441 if (flags & eAnimation) {
2442 mAnimTransactionPending = true;
2443 }
2444 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002445 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2446 if (CC_UNLIKELY(err != NO_ERROR)) {
2447 // just in case something goes wrong in SF, return to the
2448 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002449 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2450 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002451 break;
2452 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002454 }
2455}
2456
Mathias Agopiane57f2922012-08-09 16:29:12 -07002457uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2458{
Jesse Hall9a143922012-10-04 16:29:19 -07002459 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2460 if (dpyIdx < 0)
2461 return 0;
2462
Mathias Agopiane57f2922012-08-09 16:29:12 -07002463 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002464 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002465 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002466 const uint32_t what = s.what;
2467 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002468 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002469 disp.surface = s.surface;
2470 flags |= eDisplayTransactionNeeded;
2471 }
2472 }
2473 if (what & DisplayState::eLayerStackChanged) {
2474 if (disp.layerStack != s.layerStack) {
2475 disp.layerStack = s.layerStack;
2476 flags |= eDisplayTransactionNeeded;
2477 }
2478 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002479 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002480 if (disp.orientation != s.orientation) {
2481 disp.orientation = s.orientation;
2482 flags |= eDisplayTransactionNeeded;
2483 }
2484 if (disp.frame != s.frame) {
2485 disp.frame = s.frame;
2486 flags |= eDisplayTransactionNeeded;
2487 }
2488 if (disp.viewport != s.viewport) {
2489 disp.viewport = s.viewport;
2490 flags |= eDisplayTransactionNeeded;
2491 }
2492 }
Michael Lentine47e45402014-07-18 15:34:25 -07002493 if (what & DisplayState::eDisplaySizeChanged) {
2494 if (disp.width != s.width) {
2495 disp.width = s.width;
2496 flags |= eDisplayTransactionNeeded;
2497 }
2498 if (disp.height != s.height) {
2499 disp.height = s.height;
2500 flags |= eDisplayTransactionNeeded;
2501 }
2502 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 }
2504 return flags;
2505}
2506
2507uint32_t SurfaceFlinger::setClientStateLocked(
2508 const sp<Client>& client,
2509 const layer_state_t& s)
2510{
2511 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002512 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002513 if (layer != 0) {
2514 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002515 bool geometryAppliesWithResize =
2516 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002517 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002518 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002519 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002520 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002521 }
2522 if (what & layer_state_t::eLayerChanged) {
2523 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002524 const auto& p = layer->getParent();
2525 if (p == nullptr) {
2526 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2527 if (layer->setLayer(s.z) && idx >= 0) {
2528 mCurrentState.layersSortedByZ.removeAt(idx);
2529 mCurrentState.layersSortedByZ.add(layer);
2530 // we need traversal (state changed)
2531 // AND transaction (list changed)
2532 flags |= eTransactionNeeded|eTraversalNeeded;
2533 }
2534 } else {
2535 if (p->setChildLayer(layer, s.z)) {
2536 flags |= eTransactionNeeded|eTraversalNeeded;
2537 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002538 }
2539 }
2540 if (what & layer_state_t::eSizeChanged) {
2541 if (layer->setSize(s.w, s.h)) {
2542 flags |= eTraversalNeeded;
2543 }
2544 }
2545 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002547 flags |= eTraversalNeeded;
2548 }
2549 if (what & layer_state_t::eMatrixChanged) {
2550 if (layer->setMatrix(s.matrix))
2551 flags |= eTraversalNeeded;
2552 }
2553 if (what & layer_state_t::eTransparentRegionChanged) {
2554 if (layer->setTransparentRegionHint(s.transparentRegion))
2555 flags |= eTraversalNeeded;
2556 }
Dan Stoza23116082015-06-18 14:58:39 -07002557 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002558 if (layer->setFlags(s.flags, s.mask))
2559 flags |= eTraversalNeeded;
2560 }
2561 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002562 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002563 flags |= eTraversalNeeded;
2564 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002565 if (what & layer_state_t::eFinalCropChanged) {
2566 if (layer->setFinalCrop(s.finalCrop))
2567 flags |= eTraversalNeeded;
2568 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002569 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002570 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002571 // We only allow setting layer stacks for top level layers,
2572 // everything else inherits layer stack from its parent.
2573 if (layer->hasParent()) {
2574 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2575 layer->getName().string());
2576 } else if (idx < 0) {
2577 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2578 "that also does not appear in the top level layer list. Something"
2579 " has gone wrong.", layer->getName().string());
2580 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002581 mCurrentState.layersSortedByZ.removeAt(idx);
2582 mCurrentState.layersSortedByZ.add(layer);
2583 // we need traversal (state changed)
2584 // AND transaction (list changed)
2585 flags |= eTransactionNeeded|eTraversalNeeded;
2586 }
2587 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002588 if (what & layer_state_t::eDeferTransaction) {
2589 layer->deferTransactionUntil(s.handle, s.frameNumber);
2590 // We don't trigger a traversal here because if no other state is
2591 // changed, we don't want this to cause any more work
2592 }
Robert Carr1db73f62016-12-21 12:58:51 -08002593 if (what & layer_state_t::eReparentChildren) {
2594 if (layer->reparentChildren(s.reparentHandle)) {
2595 flags |= eTransactionNeeded|eTraversalNeeded;
2596 }
2597 }
Robert Carrc3574f72016-03-24 12:19:32 -07002598 if (what & layer_state_t::eOverrideScalingModeChanged) {
2599 layer->setOverrideScalingMode(s.overrideScalingMode);
2600 // We don't trigger a traversal here because if no other state is
2601 // changed, we don't want this to cause any more work
2602 }
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05002603 if (what & layer_state_t::eLayerInfoChanged) {
2604 layer->setInfo(s.type, s.appid);
2605 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002606 }
2607 return flags;
2608}
2609
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002610status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002611 const String8& name,
2612 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002613 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
2615 sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002617 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002618 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002619 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002620 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002621 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002622
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002623 status_t result = NO_ERROR;
2624
2625 sp<Layer> layer;
2626
Mathias Agopian3165cc22012-08-08 19:42:09 -07002627 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2628 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002629 result = createNormalLayer(client,
2630 name, w, h, flags, format,
2631 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002633 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002634 result = createDimLayer(client,
2635 name, w, h, flags,
2636 handle, gbp, &layer);
2637 break;
2638 default:
2639 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 break;
2641 }
2642
Dan Stoza7d89d062015-04-30 13:29:25 -07002643 if (result != NO_ERROR) {
2644 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002645 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002646
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07002648 if (result != NO_ERROR) {
2649 return result;
2650 }
Irvelffc9efc2016-07-27 15:16:37 -07002651 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002652
2653 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002654 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002655}
2656
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002657status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2658 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2659 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660{
2661 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002662 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 case PIXEL_FORMAT_TRANSPARENT:
2664 case PIXEL_FORMAT_TRANSLUCENT:
2665 format = PIXEL_FORMAT_RGBA_8888;
2666 break;
2667 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002668 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 break;
2670 }
2671
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002672 *outLayer = new Layer(this, client, name, w, h, flags);
2673 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2674 if (err == NO_ERROR) {
2675 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002676 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002678
2679 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2680 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681}
2682
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002683status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2684 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2685 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002686{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002687 *outLayer = new LayerDim(this, client, name, w, h, flags);
2688 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002689 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002690 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002691}
2692
Mathias Agopianac9fa422013-02-11 16:40:36 -08002693status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694{
Mathias Agopian67106042013-03-14 19:18:13 -07002695 // called by the window manager when it wants to remove a Layer
2696 status_t err = NO_ERROR;
2697 sp<Layer> l(client->getLayerUser(handle));
2698 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002699 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002700 err = removeLayer(l);
2701 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2702 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002703 }
2704 return err;
2705}
2706
Mathias Agopian13127d82013-03-05 17:47:11 -08002707status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002708{
Mathias Agopian67106042013-03-14 19:18:13 -07002709 // called by ~LayerCleaner() when all references to the IBinder (handle)
2710 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002711 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Mathias Agopianb60314a2012-04-10 22:09:54 -07002714// ---------------------------------------------------------------------------
2715
Andy McFadden13a082e2012-08-24 10:16:42 -07002716void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002717 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002718 Vector<ComposerState> state;
2719 Vector<DisplayState> displays;
2720 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002721 d.what = DisplayState::eDisplayProjectionChanged |
2722 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002723 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002724 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002725 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002726 d.frame.makeInvalid();
2727 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002728 d.width = 0;
2729 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002730 displays.add(d);
2731 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002732 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002733
Dan Stoza9e56aa02015-11-02 13:00:03 -08002734 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2735 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002736 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002737}
2738
2739void SurfaceFlinger::initializeDisplays() {
2740 class MessageScreenInitialized : public MessageBase {
2741 SurfaceFlinger* flinger;
2742 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002743 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002744 virtual bool handler() {
2745 flinger->onInitializeDisplays();
2746 return true;
2747 }
2748 };
2749 sp<MessageBase> msg = new MessageScreenInitialized(this);
2750 postMessageAsync(msg); // we may be called from main thread, use async message
2751}
2752
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002753void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2754 int mode) {
2755 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2756 this);
2757 int32_t type = hw->getDisplayType();
2758 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002759
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002760 if (mode == currentMode) {
2761 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002762 return;
2763 }
2764
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002765 hw->setPowerMode(mode);
2766 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2767 ALOGW("Trying to set power mode for virtual display");
2768 return;
2769 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002770
Irvelffc9efc2016-07-27 15:16:37 -07002771 if (mInterceptor.isEnabled()) {
2772 Mutex::Autolock _l(mStateLock);
2773 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2774 if (idx < 0) {
2775 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2776 return;
2777 }
2778 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2779 }
2780
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002781 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002782 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002783 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002784 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2785 // FIXME: eventthread only knows about the main display right now
2786 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002787 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002788 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002790 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002791 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002792 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002793
2794 struct sched_param param = {0};
2795 param.sched_priority = 1;
2796 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2797 ALOGW("Couldn't set SCHED_FIFO on display on");
2798 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002799 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002800 // Turn off the display
2801 struct sched_param param = {0};
2802 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2803 ALOGW("Couldn't set SCHED_OTHER on display off");
2804 }
2805
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002806 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002807 disableHardwareVsync(true); // also cancels any in-progress resync
2808
Mathias Agopiancde87a32012-09-13 14:09:01 -07002809 // FIXME: eventthread only knows about the main display right now
2810 mEventThread->onScreenReleased();
2811 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002812
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002813 getHwComposer().setPowerMode(type, mode);
2814 mVisibleRegionsDirty = true;
2815 // from this point on, SF will stop drawing on this display
2816 } else {
2817 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002818 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002819}
2820
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002821void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2822 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002823 SurfaceFlinger& mFlinger;
2824 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002825 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002826 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002827 MessageSetPowerMode(SurfaceFlinger& flinger,
2828 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2829 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002830 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002831 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002832 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002833 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002834 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002835 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002836 ALOGW("Attempt to set power mode = %d for virtual display",
2837 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002838 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002839 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002840 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002841 return true;
2842 }
2843 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002844 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002845 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002846}
2847
2848// ---------------------------------------------------------------------------
2849
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2851{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002852 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002853
Mathias Agopianbd115332013-04-18 16:41:04 -07002854 IPCThreadState* ipc = IPCThreadState::self();
2855 const int pid = ipc->getCallingPid();
2856 const int uid = ipc->getCallingUid();
2857 if ((uid != AID_SHELL) &&
2858 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002859 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002860 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002862 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002863 // (this would indicate SF is stuck, but we want to be able to
2864 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002865 status_t err = mStateLock.timedLock(s2ns(1));
2866 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002867 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002868 result.appendFormat(
2869 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2870 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002871 }
2872
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002873 bool dumpAll = true;
2874 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002875 size_t numArgs = args.size();
2876 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002877 if ((index < numArgs) &&
2878 (args[index] == String16("--list"))) {
2879 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002880 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002881 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002882 }
2883
2884 if ((index < numArgs) &&
2885 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002886 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002887 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002888 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002889 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002890
2891 if ((index < numArgs) &&
2892 (args[index] == String16("--latency-clear"))) {
2893 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002894 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002895 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002896 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002897
2898 if ((index < numArgs) &&
2899 (args[index] == String16("--dispsync"))) {
2900 index++;
2901 mPrimaryDispSync.dump(result);
2902 dumpAll = false;
2903 }
Dan Stozab90cf072015-03-05 11:05:59 -08002904
2905 if ((index < numArgs) &&
2906 (args[index] == String16("--static-screen"))) {
2907 index++;
2908 dumpStaticScreenStats(result);
2909 dumpAll = false;
2910 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002911
2912 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002913 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08002914 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002915 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08002916 dumpAll = false;
2917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002919
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002920 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002921 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002922 }
2923
Mathias Agopian9795c422009-08-26 16:36:26 -07002924 if (locked) {
2925 mStateLock.unlock();
2926 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002927 }
2928 write(fd, result.string(), result.size());
2929 return NO_ERROR;
2930}
2931
Dan Stozac7014012014-02-14 15:03:43 -08002932void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2933 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002934{
Robert Carr2047fae2016-11-28 14:09:09 -08002935 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002936 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002937 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002938}
2939
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002940void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002941 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002942{
2943 String8 name;
2944 if (index < args.size()) {
2945 name = String8(args[index]);
2946 index++;
2947 }
2948
Dan Stoza9e56aa02015-11-02 13:00:03 -08002949 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2950 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002951 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002952
2953 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002954 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002955 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002956 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002957 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002958 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002959 }
Robert Carr2047fae2016-11-28 14:09:09 -08002960 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002961 }
2962}
2963
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002964void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002965 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002966{
2967 String8 name;
2968 if (index < args.size()) {
2969 name = String8(args[index]);
2970 index++;
2971 }
2972
Robert Carr2047fae2016-11-28 14:09:09 -08002973 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002974 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002975 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002976 }
Robert Carr2047fae2016-11-28 14:09:09 -08002977 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002978
Svetoslavd85084b2014-03-20 10:28:31 -07002979 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002980}
2981
Jamie Gennis6547ff42013-07-16 20:12:42 -07002982// This should only be called from the main thread. Otherwise it would need
2983// the lock and should use mCurrentState rather than mDrawingState.
2984void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002985 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07002986 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002987 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07002988
2989 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2990}
2991
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002992void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07002993{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002994 result.append(" [sf");
Andy McFadden4803b742012-09-24 19:07:20 -07002995#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002996 result.append(" HAS_CONTEXT_PRIORITY");
Andy McFadden4803b742012-09-24 19:07:20 -07002997#endif
2998#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002999 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Andy McFadden4803b742012-09-24 19:07:20 -07003000#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003001 if (isLayerTripleBufferingDisabled())
3002 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003003 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003004}
3005
Dan Stozab90cf072015-03-05 11:05:59 -08003006void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3007{
3008 result.appendFormat("Static screen stats:\n");
3009 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3010 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3011 float percent = 100.0f *
3012 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3013 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3014 b + 1, bucketTimeSec, percent);
3015 }
3016 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3017 float percent = 100.0f *
3018 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3019 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3020 NUM_BUCKETS - 1, bucketTimeSec, percent);
3021}
3022
Dan Stozae77c7662016-05-13 11:37:28 -07003023void SurfaceFlinger::recordBufferingStats(const char* layerName,
3024 std::vector<OccupancyTracker::Segment>&& history) {
3025 Mutex::Autolock lock(mBufferingStatsMutex);
3026 auto& stats = mBufferingStats[layerName];
3027 for (const auto& segment : history) {
3028 if (!segment.usedThirdBuffer) {
3029 stats.twoBufferTime += segment.totalTime;
3030 }
3031 if (segment.occupancyAverage < 1.0f) {
3032 stats.doubleBufferedTime += segment.totalTime;
3033 } else if (segment.occupancyAverage < 2.0f) {
3034 stats.tripleBufferedTime += segment.totalTime;
3035 }
3036 ++stats.numSegments;
3037 stats.totalTime += segment.totalTime;
3038 }
3039}
3040
Brian Andersond6927fb2016-07-23 23:37:30 -07003041void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3042 result.appendFormat("Layer frame timestamps:\n");
3043
3044 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3045 const size_t count = currentLayers.size();
3046 for (size_t i=0 ; i<count ; i++) {
3047 currentLayers[i]->dumpFrameEvents(result);
3048 }
3049}
3050
Dan Stozae77c7662016-05-13 11:37:28 -07003051void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3052 result.append("Buffering stats:\n");
3053 result.append(" [Layer name] <Active time> <Two buffer> "
3054 "<Double buffered> <Triple buffered>\n");
3055 Mutex::Autolock lock(mBufferingStatsMutex);
3056 typedef std::tuple<std::string, float, float, float> BufferTuple;
3057 std::map<float, BufferTuple, std::greater<float>> sorted;
3058 for (const auto& statsPair : mBufferingStats) {
3059 const char* name = statsPair.first.c_str();
3060 const BufferingStats& stats = statsPair.second;
3061 if (stats.numSegments == 0) {
3062 continue;
3063 }
3064 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3065 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3066 stats.totalTime;
3067 float doubleBufferRatio = static_cast<float>(
3068 stats.doubleBufferedTime) / stats.totalTime;
3069 float tripleBufferRatio = static_cast<float>(
3070 stats.tripleBufferedTime) / stats.totalTime;
3071 sorted.insert({activeTime, {name, twoBufferRatio,
3072 doubleBufferRatio, tripleBufferRatio}});
3073 }
3074 for (const auto& sortedPair : sorted) {
3075 float activeTime = sortedPair.first;
3076 const BufferTuple& values = sortedPair.second;
3077 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3078 std::get<0>(values).c_str(), activeTime,
3079 std::get<1>(values), std::get<2>(values),
3080 std::get<3>(values));
3081 }
3082 result.append("\n");
3083}
3084
3085
Mathias Agopian74d211a2013-04-22 16:55:35 +02003086void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3087 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003088{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003089 bool colorize = false;
3090 if (index < args.size()
3091 && (args[index] == String16("--color"))) {
3092 colorize = true;
3093 index++;
3094 }
3095
3096 Colorizer colorizer(colorize);
3097
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003098 // figure out if we're stuck somewhere
3099 const nsecs_t now = systemTime();
3100 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3101 const nsecs_t inTransaction(mDebugInTransaction);
3102 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3103 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3104
3105 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003106 * Dump library configuration.
3107 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003108
3109 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003110 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003111 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003112 appendSfConfigString(result);
3113 appendUiConfigString(result);
3114 appendGuiConfigString(result);
3115 result.append("\n");
3116
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003117 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003118 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003119 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003120 result.append(SyncFeatures::getInstance().toString());
3121 result.append("\n");
3122
Dan Stoza9e56aa02015-11-02 13:00:03 -08003123 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3124
Andy McFadden41d67d72014-04-25 16:58:34 -07003125 colorizer.bold(result);
3126 result.append("DispSync configuration: ");
3127 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003128 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3129 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003130 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3131 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003132 result.append("\n");
3133
Dan Stozab90cf072015-03-05 11:05:59 -08003134 // Dump static screen stats
3135 result.append("\n");
3136 dumpStaticScreenStats(result);
3137 result.append("\n");
3138
Dan Stozae77c7662016-05-13 11:37:28 -07003139 dumpBufferingStats(result);
3140
Andy McFadden4803b742012-09-24 19:07:20 -07003141 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003142 * Dump the visible layer list
3143 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003144 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003146 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003147 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003148 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003149 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003150
3151 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003152 * Dump Display state
3153 */
3154
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003155 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003156 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003157 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003158 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3159 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003160 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003161 }
3162
3163 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003164 * Dump SurfaceFlinger global state
3165 */
3166
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003167 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003168 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003169 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003170
Mathias Agopian888c8222012-08-04 21:10:38 -07003171 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003172 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003173
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003174 colorizer.bold(result);
3175 result.appendFormat("EGL implementation : %s\n",
3176 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3177 colorizer.reset(result);
3178 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003179 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003180
Mathias Agopian875d8e12013-06-07 15:35:48 -07003181 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003182
Mathias Agopian42977342012-08-05 00:40:46 -07003183 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003184 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3185 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003186 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003187 " last eglSwapBuffers() time: %f us\n"
3188 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003189 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003190 " refresh-rate : %f fps\n"
3191 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003192 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003193 " gpu_to_cpu_unsupported : %d\n"
3194 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003195 mLastSwapBufferTime/1000.0,
3196 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003197 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003198 1e9 / activeConfig->getVsyncPeriod(),
3199 activeConfig->getDpiX(),
3200 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003201 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003202
Mathias Agopian74d211a2013-04-22 16:55:35 +02003203 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003204 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003205
Mathias Agopian74d211a2013-04-22 16:55:35 +02003206 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003207 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003208
3209 /*
3210 * VSYNC state
3211 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003212 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003213 result.append("\n");
3214
3215 /*
3216 * HWC layer minidump
3217 */
3218 for (size_t d = 0; d < mDisplays.size(); d++) {
3219 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3220 int32_t hwcId = displayDevice->getHwcDisplayId();
3221 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3222 continue;
3223 }
3224
3225 result.appendFormat("Display %d HWC layers:\n", hwcId);
3226 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003227 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003228 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003229 });
Dan Stozae22aec72016-08-01 13:20:59 -07003230 result.append("\n");
3231 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003232
3233 /*
3234 * Dump HWComposer state
3235 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003236 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003237 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003238 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003239 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003240 result.appendFormat(" h/w composer %s\n",
3241 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003242 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003243
3244 /*
3245 * Dump gralloc state
3246 */
3247 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3248 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003249}
3250
Mathias Agopian13127d82013-03-05 17:47:11 -08003251const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003252SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003253 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003254 wp<IBinder> dpy;
3255 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3256 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3257 dpy = mDisplays.keyAt(i);
3258 break;
3259 }
3260 }
3261 if (dpy == NULL) {
3262 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3263 // Just use the primary display so we have something to return
3264 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3265 }
3266 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003267}
3268
Keun young Park63f165f2012-08-31 10:53:36 -07003269bool SurfaceFlinger::startDdmConnection()
3270{
3271 void* libddmconnection_dso =
3272 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3273 if (!libddmconnection_dso) {
3274 return false;
3275 }
3276 void (*DdmConnection_start)(const char* name);
3277 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003278 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003279 if (!DdmConnection_start) {
3280 dlclose(libddmconnection_dso);
3281 return false;
3282 }
3283 (*DdmConnection_start)(getServiceName());
3284 return true;
3285}
3286
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003287status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288 switch (code) {
3289 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003290 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003292 case CLEAR_ANIMATION_FRAME_STATS:
3293 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003294 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003295 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296 {
3297 // codes that require permission check
3298 IPCThreadState* ipc = IPCThreadState::self();
3299 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003300 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003301 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003302 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003303 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003304 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003305 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003306 break;
3307 }
Robert Carr1db73f62016-12-21 12:58:51 -08003308 /*
3309 * Calling setTransactionState is safe, because you need to have been
3310 * granted a reference to Client* and Handle* to do anything with it.
3311 *
3312 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3313 */
3314 case SET_TRANSACTION_STATE:
3315 case CREATE_SCOPED_CONNECTION:
3316 {
3317 return OK;
3318 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003319 case CAPTURE_SCREEN:
3320 {
3321 // codes that require permission check
3322 IPCThreadState* ipc = IPCThreadState::self();
3323 const int pid = ipc->getCallingPid();
3324 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003325 if ((uid != AID_GRAPHICS) &&
3326 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003327 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003328 return PERMISSION_DENIED;
3329 }
3330 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003331 }
3332 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003333 return OK;
3334}
3335
3336status_t SurfaceFlinger::onTransact(
3337 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3338{
3339 status_t credentialCheck = CheckTransactCodeCredentials(code);
3340 if (credentialCheck != OK) {
3341 return credentialCheck;
3342 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003344 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3345 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003346 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003347 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003348 IPCThreadState* ipc = IPCThreadState::self();
3349 const int pid = ipc->getCallingPid();
3350 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003351 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003352 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003353 return PERMISSION_DENIED;
3354 }
3355 int n;
3356 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003357 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003358 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 return NO_ERROR;
3360 case 1002: // SHOW_UPDATES
3361 n = data.readInt32();
3362 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003363 invalidateHwcGeometry();
3364 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003367 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003368 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003370 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003371 setTransactionFlags(
3372 eTransactionNeeded|
3373 eDisplayTransactionNeeded|
3374 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003375 return NO_ERROR;
3376 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003377 case 1006:{ // send empty update
3378 signalRefresh();
3379 return NO_ERROR;
3380 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003381 case 1008: // toggle use of hw composer
3382 n = data.readInt32();
3383 mDebugDisableHWC = n ? 1 : 0;
3384 invalidateHwcGeometry();
3385 repaintEverything();
3386 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003387 case 1009: // toggle use of transform hint
3388 n = data.readInt32();
3389 mDebugDisableTransformHint = n ? 1 : 0;
3390 invalidateHwcGeometry();
3391 repaintEverything();
3392 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003394 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003395 reply->writeInt32(0);
3396 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003397 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003398 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003399 return NO_ERROR;
3400 case 1013: {
3401 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003402 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3403 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003404 return NO_ERROR;
3405 }
3406 case 1014: {
3407 // daltonize
3408 n = data.readInt32();
3409 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003410 case 1:
3411 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3412 break;
3413 case 2:
3414 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3415 break;
3416 case 3:
3417 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3418 break;
3419 default:
3420 mDaltonizer.setType(ColorBlindnessType::None);
3421 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003422 }
3423 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003424 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003425 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003426 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003427 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003428 invalidateHwcGeometry();
3429 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003430 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003431 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003432 case 1015: {
3433 // apply a color matrix
3434 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003435 if (n) {
3436 // color matrix is sent as mat3 matrix followed by vec3
3437 // offset, then packed into a mat4 where the last row is
3438 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003439 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003440 for (size_t j = 0; j < 4; j++) {
3441 mColorMatrix[i][j] = data.readFloat();
3442 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003443 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003444 } else {
3445 mColorMatrix = mat4();
3446 }
3447 invalidateHwcGeometry();
3448 repaintEverything();
3449 return NO_ERROR;
3450 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003451 // This is an experimental interface
3452 // Needs to be shifted to proper binder interface when we productize
3453 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003454 n = data.readInt32();
3455 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003456 return NO_ERROR;
3457 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003458 case 1017: {
3459 n = data.readInt32();
3460 mForceFullDamage = static_cast<bool>(n);
3461 return NO_ERROR;
3462 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003463 case 1018: { // Modify Choreographer's phase offset
3464 n = data.readInt32();
3465 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3466 return NO_ERROR;
3467 }
3468 case 1019: { // Modify SurfaceFlinger's phase offset
3469 n = data.readInt32();
3470 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3471 return NO_ERROR;
3472 }
Irvel468051e2016-06-13 16:44:44 -07003473 case 1020: { // Layer updates interceptor
3474 n = data.readInt32();
3475 if (n) {
3476 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003477 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003478 }
3479 else{
3480 ALOGV("Interceptor disabled");
3481 mInterceptor.disable();
3482 }
3483 return NO_ERROR;
3484 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003485 case 1021: { // Disable HWC virtual displays
3486 n = data.readInt32();
3487 mUseHwcVirtualDisplays = !n;
3488 return NO_ERROR;
3489 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003490 }
3491 }
3492 return err;
3493}
3494
Mathias Agopian53331da2011-08-22 21:44:41 -07003495void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003496 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003497 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003498}
3499
Mathias Agopian59119e62010-10-11 12:37:43 -07003500// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003501// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003502// ---------------------------------------------------------------------------
3503
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003504/* The code below is here to handle b/8734824
3505 *
3506 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003507 * from the surfaceflinger thread to the calling binder thread, where they
3508 * are executed. This allows the calling thread in the calling process to be
3509 * reused and not depend on having "enough" binder threads to handle the
3510 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003511 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003512class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003513 /* Parts of GraphicProducerWrapper are run on two different threads,
3514 * communicating by sending messages via Looper but also by shared member
3515 * data. Coherence maintenance is subtle and in places implicit (ugh).
3516 *
3517 * Don't rely on Looper's sendMessage/handleMessage providing
3518 * release/acquire semantics for any data not actually in the Message.
3519 * Data going from surfaceflinger to binder threads needs to be
3520 * synchronized explicitly.
3521 *
3522 * Barrier open/wait do provide release/acquire semantics. This provides
3523 * implicit synchronization for data coming back from binder to
3524 * surfaceflinger threads.
3525 */
3526
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003527 sp<IGraphicBufferProducer> impl;
3528 sp<Looper> looper;
3529 status_t result;
3530 bool exitPending;
3531 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003532 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533 uint32_t code;
3534 Parcel const* data;
3535 Parcel* reply;
3536
3537 enum {
3538 MSG_API_CALL,
3539 MSG_EXIT
3540 };
3541
3542 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003543 * Called on surfaceflinger thread. This is called by our "fake"
3544 * BpGraphicBufferProducer. We package the data and reply Parcel and
3545 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003546 */
3547 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003548 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003549 this->code = code;
3550 this->data = &data;
3551 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003552 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003553 // if we've exited, we run the message synchronously right here.
3554 // note (JH): as far as I can tell from looking at the code, this
3555 // never actually happens. if it does, i'm not sure if it happens
3556 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003557 handleMessage(Message(MSG_API_CALL));
3558 } else {
3559 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003560 // Prevent stores to this->{code, data, reply} from being
3561 // reordered later than the construction of Message.
3562 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003563 looper->sendMessage(this, Message(MSG_API_CALL));
3564 barrier.wait();
3565 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003566 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003567 }
3568
3569 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003570 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003571 * call the real BpGraphicBufferProducer.
3572 */
3573 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003574 int what = message.what;
3575 // Prevent reads below from happening before the read from Message
3576 atomic_thread_fence(memory_order_acquire);
3577 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003578 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003579 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003580 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003581 exitRequested = true;
3582 }
3583 }
3584
3585public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003586 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003587 : impl(impl),
3588 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003589 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003590 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003591 exitRequested(false),
3592 code(0),
3593 data(NULL),
3594 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003595 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003596
Jesse Hallb154c422014-07-13 12:47:02 -07003597 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003598 status_t waitForResponse() {
3599 do {
3600 looper->pollOnce(-1);
3601 } while (!exitRequested);
3602 return result;
3603 }
3604
Jesse Hallb154c422014-07-13 12:47:02 -07003605 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003606 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003607 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003608 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003609 // Ensure this->result is visible to the binder thread before it
3610 // handles the message.
3611 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003612 looper->sendMessage(this, Message(MSG_EXIT));
3613 }
3614};
3615
3616
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003617status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3618 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003619 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003620 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003621 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003622
3623 if (CC_UNLIKELY(display == 0))
3624 return BAD_VALUE;
3625
3626 if (CC_UNLIKELY(producer == 0))
3627 return BAD_VALUE;
3628
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003629 // if we have secure windows on this display, never allow the screen capture
3630 // unless the producer interface is local (i.e.: we can take a screenshot for
3631 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003632 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003633
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003634 // Convert to surfaceflinger's internal rotation type.
3635 Transform::orientation_flags rotationFlags;
3636 switch (rotation) {
3637 case ISurfaceComposer::eRotateNone:
3638 rotationFlags = Transform::ROT_0;
3639 break;
3640 case ISurfaceComposer::eRotate90:
3641 rotationFlags = Transform::ROT_90;
3642 break;
3643 case ISurfaceComposer::eRotate180:
3644 rotationFlags = Transform::ROT_180;
3645 break;
3646 case ISurfaceComposer::eRotate270:
3647 rotationFlags = Transform::ROT_270;
3648 break;
3649 default:
3650 rotationFlags = Transform::ROT_0;
3651 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3652 break;
3653 }
3654
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003655 class MessageCaptureScreen : public MessageBase {
3656 SurfaceFlinger* flinger;
3657 sp<IBinder> display;
3658 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003659 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003660 uint32_t reqWidth, reqHeight;
3661 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003662 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003663 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003664 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003665 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003666 public:
3667 MessageCaptureScreen(SurfaceFlinger* flinger,
3668 const sp<IBinder>& display,
3669 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003670 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003671 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003672 bool useIdentityTransform,
3673 Transform::orientation_flags rotation,
3674 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003675 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003676 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003677 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003678 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003679 rotation(rotation), result(PERMISSION_DENIED),
3680 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003681 {
3682 }
3683 status_t getResult() const {
3684 return result;
3685 }
3686 virtual bool handler() {
3687 Mutex::Autolock _l(flinger->mStateLock);
3688 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003689 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003690 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003691 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003692 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003693 return true;
3694 }
3695 };
3696
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003697 // this creates a "fake" BBinder which will serve as a "fake" remote
3698 // binder to receive the marshaled calls and forward them to the
3699 // real remote (a BpGraphicBufferProducer)
3700 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3701
3702 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3703 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003704 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003705 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003706 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003707 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003708
3709 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003710 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003711 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003712 }
3713 return res;
3714}
3715
Mathias Agopian180f10d2013-04-10 22:55:41 -07003716
3717void SurfaceFlinger::renderScreenImplLocked(
3718 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003719 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003720 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003721 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003722{
3723 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003724 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003725
3726 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003727 const int32_t hw_w = hw->getWidth();
3728 const int32_t hw_h = hw->getHeight();
3729 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003730 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003731
Dan Stozac1879002014-05-22 15:59:05 -07003732 // if a default or invalid sourceCrop is passed in, set reasonable values
3733 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3734 !sourceCrop.isValid()) {
3735 sourceCrop.setLeftTop(Point(0, 0));
3736 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3737 }
3738
3739 // ensure that sourceCrop is inside screen
3740 if (sourceCrop.left < 0) {
3741 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3742 }
Dan Stozabe31f442014-06-11 11:20:54 -07003743 if (sourceCrop.right > hw_w) {
3744 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003745 }
3746 if (sourceCrop.top < 0) {
3747 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3748 }
Dan Stozabe31f442014-06-11 11:20:54 -07003749 if (sourceCrop.bottom > hw_h) {
3750 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003751 }
3752
Mathias Agopian180f10d2013-04-10 22:55:41 -07003753 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003754 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003755
3756 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003757 engine.setViewportAndProjection(
3758 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003759 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003760
3761 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003762 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003763
Robert Carr1f0a16a2016-10-24 16:27:39 -07003764 // We loop through the first level of layers without traversing,
3765 // as we need to interpret min/max layer Z in the top level Z space.
3766 for (const auto& layer : mDrawingState.layersSortedByZ) {
3767 if (layer->getLayerStack() != hw->getLayerStack()) {
3768 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003769 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003770 const Layer::State& state(layer->getDrawingState());
3771 if (state.z < minLayerZ || state.z > maxLayerZ) {
3772 continue;
3773 }
3774 layer->traverseInZOrder([&](Layer* layer) {
3775 if (!layer->isVisible()) {
3776 return;
3777 }
3778 if (filtering) layer->setFiltering(true);
3779 layer->draw(hw, useIdentityTransform);
3780 if (filtering) layer->setFiltering(false);
3781 });
3782 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003783
Mathias Agopian931bda12013-08-28 18:11:46 -07003784 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003785}
3786
3787
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003788status_t SurfaceFlinger::captureScreenImplLocked(
3789 const sp<const DisplayDevice>& hw,
3790 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003791 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003792 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003793 bool useIdentityTransform, Transform::orientation_flags rotation,
3794 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003795{
3796 ATRACE_CALL();
3797
Mathias Agopian180f10d2013-04-10 22:55:41 -07003798 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003799 uint32_t hw_w = hw->getWidth();
3800 uint32_t hw_h = hw->getHeight();
3801
3802 if (rotation & Transform::ROT_90) {
3803 std::swap(hw_w, hw_h);
3804 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003805
Mathias Agopian180f10d2013-04-10 22:55:41 -07003806 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3807 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3808 reqWidth, reqHeight, hw_w, hw_h);
3809 return BAD_VALUE;
3810 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003811
Mathias Agopian180f10d2013-04-10 22:55:41 -07003812 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3813 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3814
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003815 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003816 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003817 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003818 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3819 (state.z < minLayerZ || state.z > maxLayerZ)) {
3820 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003821 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003822 layer->traverseInZOrder([&](Layer *layer) {
3823 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3824 layer->isSecure());
3825 });
3826 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003827
3828 if (!isLocalScreenshot && secureLayerIsVisible) {
3829 ALOGW("FB is protected: PERMISSION_DENIED");
3830 return PERMISSION_DENIED;
3831 }
3832
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003833 // create a surface (because we're a producer, and we need to
3834 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003835 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003836
3837 // Put the screenshot Surface into async mode so that
3838 // Layer::headFenceHasSignaled will always return true and we'll latch the
3839 // first buffer regardless of whether or not its acquire fence has
3840 // signaled. This is needed to avoid a race condition in the rotation
3841 // animation. See b/30209608
3842 sur->setAsyncMode(true);
3843
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003844 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003845
Michael Lentine5a16a622015-05-21 13:48:24 -07003846 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3847 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003848 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3849 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003850
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003851 int err = 0;
3852 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003853 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003854 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3855 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003856
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003857 if (err == NO_ERROR) {
3858 ANativeWindowBuffer* buffer;
3859 /* TODO: Once we have the sync framework everywhere this can use
3860 * server-side waits on the fence that dequeueBuffer returns.
3861 */
3862 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3863 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003864 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003865 // create an EGLImage from the buffer so we can later
3866 // turn it into a texture
3867 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3868 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3869 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003870 // this binds the given EGLImage as a framebuffer for the
3871 // duration of this scope.
3872 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3873 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003874 // this will in fact render into our dequeued buffer
3875 // via an FBO, which means we didn't have to create
3876 // an EGLSurface and therefore we're not
3877 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003878 renderScreenImplLocked(
3879 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3880 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003881
Riley Andrews86639902014-08-15 12:27:24 -07003882 // Attempt to create a sync khr object that can produce a sync point. If that
3883 // isn't available, create a non-dupable sync object in the fallback path and
3884 // wait on it directly.
3885 EGLSyncKHR sync;
3886 if (!DEBUG_SCREENSHOTS) {
3887 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003888 // native fence fd will not be populated until flush() is done.
3889 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003890 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003891 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003892 }
Riley Andrews86639902014-08-15 12:27:24 -07003893 if (sync != EGL_NO_SYNC_KHR) {
3894 // get the sync fd
3895 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3896 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3897 ALOGW("captureScreen: failed to dup sync khr object");
3898 syncFd = -1;
3899 }
3900 eglDestroySyncKHR(mEGLDisplay, sync);
3901 } else {
3902 // fallback path
3903 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3904 if (sync != EGL_NO_SYNC_KHR) {
3905 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3906 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3907 EGLint eglErr = eglGetError();
3908 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3909 ALOGW("captureScreen: fence wait timed out");
3910 } else {
3911 ALOGW_IF(eglErr != EGL_SUCCESS,
3912 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3913 }
3914 eglDestroySyncKHR(mEGLDisplay, sync);
3915 } else {
3916 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3917 }
3918 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003919 if (DEBUG_SCREENSHOTS) {
3920 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3921 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3922 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3923 hw, minLayerZ, maxLayerZ);
3924 delete [] pixels;
3925 }
3926
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003927 } else {
3928 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3929 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003930 window->cancelBuffer(window, buffer, syncFd);
3931 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003932 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003933 // destroy our image
3934 eglDestroyImageKHR(mEGLDisplay, image);
3935 } else {
3936 result = BAD_VALUE;
3937 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003938 if (buffer) {
3939 // queueBuffer takes ownership of syncFd
3940 result = window->queueBuffer(window, buffer, syncFd);
3941 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003942 }
3943 } else {
3944 result = BAD_VALUE;
3945 }
3946 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3947 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003948
Mathias Agopian74c40c02010-09-29 13:02:36 -07003949 return result;
3950}
3951
Mathias Agopiand5556842013-09-19 17:08:37 -07003952void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003953 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003954 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003955 for (size_t y=0 ; y<h ; y++) {
3956 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3957 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003958 if (p[x] != 0xFF000000) return;
3959 }
3960 }
3961 ALOGE("*** we just took a black screenshot ***\n"
3962 "requested minz=%d, maxz=%d, layerStack=%d",
3963 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003964
Robert Carr2047fae2016-11-28 14:09:09 -08003965 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003966 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003967 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003968 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3969 state.z <= maxLayerZ) {
3970 layer->traverseInZOrder([&](Layer* layer) {
3971 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3972 layer->isVisible() ? '+' : '-',
3973 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07003974 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003975 i++;
3976 });
3977 }
3978 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07003979 }
3980}
3981
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003982// ---------------------------------------------------------------------------
3983
Robert Carr2047fae2016-11-28 14:09:09 -08003984void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3985 layersSortedByZ.traverseInZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003986}
3987
Robert Carr2047fae2016-11-28 14:09:09 -08003988void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3989 layersSortedByZ.traverseInReverseZOrder(consume);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003990}
3991
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003993
3994
3995#if defined(__gl_h_)
3996#error "don't include gl/gl.h in this file"
3997#endif
3998
3999#if defined(__gl2_h_)
4000#error "don't include gl2/gl2.h in this file"
4001#endif