blob: db52d402148bb3c8e9470cc241c668bdd138947e [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>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasColorMatrix(false),
156 mHasPoweredOff(false),
157 mFrameBuckets(),
158 mTotalTime(0),
159 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160{
Steve Blocka19954a2012-01-04 20:05:49 +0000161 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162
163 // debugging stuff...
164 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700165
Mathias Agopianb4b17302013-03-20 18:36:41 -0700166 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700167 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 property_get("debug.sf.showupdates", value, "0");
170 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700171
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172 property_get("debug.sf.ddms", value, "0");
173 mDebugDDMS = atoi(value);
174 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700175 if (!startDdmConnection()) {
176 // start failed, and DDMS debugging not enabled
177 mDebugDDMS = 0;
178 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700180 ALOGI_IF(mDebugRegion, "showupdates enabled");
181 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700182
183 property_get("debug.sf.disable_backpressure", value, "0");
184 mPropagateBackpressure = !atoi(value);
185 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza3cf4bfe2016-08-02 10:27:31 -0700186
187 property_get("debug.sf.disable_hwc_vds", value, "0");
188 mUseHwcVirtualDisplays = !atoi(value);
189 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800190}
191
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800192void SurfaceFlinger::onFirstRef()
193{
194 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800195}
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197SurfaceFlinger::~SurfaceFlinger()
198{
Mathias Agopiana4912602012-07-12 14:25:33 -0700199 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
200 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
201 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202}
203
Dan Stozac7014012014-02-14 15:03:43 -0800204void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205{
206 // the window manager died on us. prepare its eulogy.
207
Andy McFadden13a082e2012-08-24 10:16:42 -0700208 // restore initial conditions (default device unblank, etc)
209 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800210
211 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700212 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800213}
214
Mathias Agopian7e27f052010-05-28 14:22:23 -0700215sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800216{
Mathias Agopian96f08192010-06-02 23:28:45 -0700217 sp<ISurfaceComposerClient> bclient;
218 sp<Client> client(new Client(this));
219 status_t err = client->initCheck();
220 if (err == NO_ERROR) {
221 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800223 return bclient;
224}
225
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700226sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
227 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700228{
229 class DisplayToken : public BBinder {
230 sp<SurfaceFlinger> flinger;
231 virtual ~DisplayToken() {
232 // no more references, this display must be terminated
233 Mutex::Autolock _l(flinger->mStateLock);
234 flinger->mCurrentState.displays.removeItem(this);
235 flinger->setTransactionFlags(eDisplayTransactionNeeded);
236 }
237 public:
238 DisplayToken(const sp<SurfaceFlinger>& flinger)
239 : flinger(flinger) {
240 }
241 };
242
243 sp<BBinder> token = new DisplayToken(this);
244
245 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700246 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700247 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700248 mCurrentState.displays.add(token, info);
249
250 return token;
251}
252
Jesse Hall6c913be2013-08-08 12:15:49 -0700253void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
254 Mutex::Autolock _l(mStateLock);
255
256 ssize_t idx = mCurrentState.displays.indexOfKey(display);
257 if (idx < 0) {
258 ALOGW("destroyDisplay: invalid display token");
259 return;
260 }
261
262 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
263 if (!info.isVirtualDisplay()) {
264 ALOGE("destroyDisplay called for non-virtual display");
265 return;
266 }
267
268 mCurrentState.displays.removeItemsAt(idx);
269 setTransactionFlags(eDisplayTransactionNeeded);
270}
271
Jesse Hall692c7232012-11-08 15:41:56 -0800272void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800273 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800274 ALOGW_IF(mBuiltinDisplays[type],
275 "Overwriting display token for display type %d", type);
276 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800277 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700278 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800279 mCurrentState.displays.add(mBuiltinDisplays[type], info);
280}
281
Mathias Agopiane57f2922012-08-09 16:29:12 -0700282sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700283 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
285 return NULL;
286 }
Jesse Hall692c7232012-11-08 15:41:56 -0800287 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700288}
289
Jamie Gennis9a78c902011-01-12 18:30:40 -0800290sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
291{
292 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
293 return gba;
294}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700295
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800296void SurfaceFlinger::bootFinished()
297{
298 const nsecs_t now = systemTime();
299 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000300 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700301 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700302
303 // wait patiently for the window manager death
304 const String16 name("window");
305 sp<IBinder> window(defaultServiceManager()->getService(name));
306 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700307 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700308 }
309
310 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700311 // formerly we would just kill the process, but we now ask it to exit so it
312 // can choose where to stop the animation.
313 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700314
315 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
316 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
317 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318}
319
Mathias Agopian3f844832013-08-07 21:24:32 -0700320void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700321 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700322 RenderEngine& engine;
323 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700324 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
326 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700327 }
328 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700329 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330 return true;
331 }
332 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700333 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700334}
335
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700336class DispSyncSource : public VSyncSource, private DispSync::Callback {
337public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700338 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000339 const char* name) :
340 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700341 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700342 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000343 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
344 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700345 mDispSync(dispSync),
346 mCallbackMutex(),
347 mCallback(),
348 mVsyncMutex(),
349 mPhaseOffset(phaseOffset),
350 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700351
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352 virtual ~DispSyncSource() {}
353
354 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700355 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700356 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000357 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700358 static_cast<DispSync::Callback*>(this));
359 if (err != NO_ERROR) {
360 ALOGE("error registering vsync callback: %s (%d)",
361 strerror(-err), err);
362 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700363 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700364 } else {
365 status_t err = mDispSync->removeEventListener(
366 static_cast<DispSync::Callback*>(this));
367 if (err != NO_ERROR) {
368 ALOGE("error unregistering vsync callback: %s (%d)",
369 strerror(-err), err);
370 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700371 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700372 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700373 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 }
375
376 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700377 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700378 mCallback = callback;
379 }
380
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700381 virtual void setPhaseOffset(nsecs_t phaseOffset) {
382 Mutex::Autolock lock(mVsyncMutex);
383
384 // Normalize phaseOffset to [0, period)
385 auto period = mDispSync->getPeriod();
386 phaseOffset %= period;
387 if (phaseOffset < 0) {
388 // If we're here, then phaseOffset is in (-period, 0). After this
389 // operation, it will be in (0, period)
390 phaseOffset += period;
391 }
392 mPhaseOffset = phaseOffset;
393
394 // If we're not enabled, we don't need to mess with the listeners
395 if (!mEnabled) {
396 return;
397 }
398
399 // Remove the listener with the old offset
400 status_t err = mDispSync->removeEventListener(
401 static_cast<DispSync::Callback*>(this));
402 if (err != NO_ERROR) {
403 ALOGE("error unregistering vsync callback: %s (%d)",
404 strerror(-err), err);
405 }
406
407 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000408 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700409 static_cast<DispSync::Callback*>(this));
410 if (err != NO_ERROR) {
411 ALOGE("error registering vsync callback: %s (%d)",
412 strerror(-err), err);
413 }
414 }
415
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416private:
417 virtual void onDispSyncEvent(nsecs_t when) {
418 sp<VSyncSource::Callback> callback;
419 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 callback = mCallback;
422
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700423 if (mTraceVsync) {
424 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700425 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700426 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 }
428
429 if (callback != NULL) {
430 callback->onVSyncEvent(when);
431 }
432 }
433
Tim Murray4a4e4a22016-04-19 16:29:23 +0000434 const char* const mName;
435
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 int mValue;
437
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700438 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700439 const String8 mVsyncOnLabel;
440 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700443
444 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700446
447 Mutex mVsyncMutex; // Protects the following
448 nsecs_t mPhaseOffset;
449 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450};
451
452void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700453 ALOGI( "SurfaceFlinger's main thread ready to run. "
454 "Initializing graphics H/W...");
455
Dan Stoza9e56aa02015-11-02 13:00:03 -0800456 { // Autolock scope
457 Mutex::Autolock _l(mStateLock);
458
459 // initialize EGL for the default display
460 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
461 eglInitialize(mEGLDisplay, NULL, NULL);
462
463 // start the EventThread
464 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
465 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800467 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
468 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000469 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800470 mEventQueue.setEventThread(mSFEventThread);
471
Tim Murrayacff43d2016-07-29 13:57:24 -0700472 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700473 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700474 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700475 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
476 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
477 }
478
Dan Stoza9e56aa02015-11-02 13:00:03 -0800479 // Get a RenderEngine for the given display / config (can't fail)
480 mRenderEngine = RenderEngine::create(mEGLDisplay,
481 HAL_PIXEL_FORMAT_RGBA_8888);
482 }
483
484 // Drop the state lock while we initialize the hardware composer. We drop
485 // the lock because on creation, it will call back into SurfaceFlinger to
486 // initialize the primary display.
487 mHwc = new HWComposer(this);
488 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
489
Jesse Hall692c7232012-11-08 15:41:56 -0800490 Mutex::Autolock _l(mStateLock);
491
Mathias Agopian875d8e12013-06-07 15:35:48 -0700492 // retrieve the EGL context that was selected/created
493 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700494
Mathias Agopianda27af92012-09-13 18:17:13 -0700495 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
496 "couldn't create EGLContext");
497
Dan Stoza9e56aa02015-11-02 13:00:03 -0800498 // make the GLContext current so that we can create textures when creating
499 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700500 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
501
Jamie Gennisd1700752013-10-14 12:22:52 -0700502 mEventControlThread = new EventControlThread(this);
503 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
504
Mathias Agopian92a979a2012-08-02 18:32:23 -0700505 // initialize our drawing state
506 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700507
Andy McFadden13a082e2012-08-24 10:16:42 -0700508 // set initial conditions (e.g. unblank default device)
509 initializeDisplays();
510
Dan Stoza4e637772016-07-28 13:31:51 -0700511 mRenderEngine->primeCache();
512
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700513 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700514 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515
Dan Stoza9e56aa02015-11-02 13:00:03 -0800516 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700517}
518
Mathias Agopiana67e4182012-06-19 17:26:12 -0700519void SurfaceFlinger::startBootAnim() {
520 // start boot animation
521 property_set("service.bootanim.exit", "0");
522 property_set("ctl.start", "bootanim");
523}
524
Mathias Agopian875d8e12013-06-07 15:35:48 -0700525size_t SurfaceFlinger::getMaxTextureSize() const {
526 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700527}
528
Mathias Agopian875d8e12013-06-07 15:35:48 -0700529size_t SurfaceFlinger::getMaxViewportDims() const {
530 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700531}
532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800534
Jamie Gennis582270d2011-08-17 18:19:00 -0700535bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800536 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800537 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800538 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700539 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800540}
541
Dan Stoza7f7da322014-05-02 15:26:25 -0700542status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
543 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700544 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700545 return BAD_VALUE;
546 }
547
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500548 if (!display.get())
549 return NAME_NOT_FOUND;
550
Jesse Hall692c7232012-11-08 15:41:56 -0800551 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700552 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800553 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700554 type = i;
555 break;
556 }
557 }
558
559 if (type < 0) {
560 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700561 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700562
Mathias Agopian8b736f12012-08-13 17:54:26 -0700563 // TODO: Not sure if display density should handled by SF any longer
564 class Density {
565 static int getDensityFromProperty(char const* propName) {
566 char property[PROPERTY_VALUE_MAX];
567 int density = 0;
568 if (property_get(propName, property, NULL) > 0) {
569 density = atoi(property);
570 }
571 return density;
572 }
573 public:
574 static int getEmuDensity() {
575 return getDensityFromProperty("qemu.sf.lcd_density"); }
576 static int getBuildDensity() {
577 return getDensityFromProperty("ro.sf.lcd_density"); }
578 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700579
Dan Stoza7f7da322014-05-02 15:26:25 -0700580 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700581
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700583 DisplayInfo info = DisplayInfo();
584
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585 float xdpi = hwConfig->getDpiX();
586 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700587
588 if (type == DisplayDevice::DISPLAY_PRIMARY) {
589 // The density of the device is provided by a build property
590 float density = Density::getBuildDensity() / 160.0f;
591 if (density == 0) {
592 // the build doesn't provide a density -- this is wrong!
593 // use xdpi instead
594 ALOGE("ro.sf.lcd_density must be defined as a build property");
595 density = xdpi / 160.0f;
596 }
597 if (Density::getEmuDensity()) {
598 // if "qemu.sf.lcd_density" is specified, it overrides everything
599 xdpi = ydpi = density = Density::getEmuDensity();
600 density /= 160.0f;
601 }
602 info.density = density;
603
604 // TODO: this needs to go away (currently needed only by webkit)
605 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
606 info.orientation = hw->getOrientation();
607 } else {
608 // TODO: where should this value come from?
609 static const int TV_DENSITY = 213;
610 info.density = TV_DENSITY / 160.0f;
611 info.orientation = 0;
612 }
613
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 info.w = hwConfig->getWidth();
615 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700616 info.xdpi = xdpi;
617 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700619 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
Andy McFadden91b2ca82014-06-13 14:04:23 -0700621 // This is how far in advance a buffer must be queued for
622 // presentation at a given time. If you want a buffer to appear
623 // on the screen at time N, you must submit the buffer before
624 // (N - presentationDeadline).
625 //
626 // Normally it's one full refresh period (to give SF a chance to
627 // latch the buffer), but this can be reduced by configuring a
628 // DispSync offset. Any additional delays introduced by the hardware
629 // composer or panel must be accounted for here.
630 //
631 // We add an additional 1ms to allow for processing time and
632 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633 info.presentationDeadline = hwConfig->getVsyncPeriod() -
634 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700635
636 // All non-virtual displays are currently considered secure.
637 info.secure = true;
638
Michael Wright28f24d02016-07-12 13:30:53 -0700639 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700640 }
641
Dan Stoza7f7da322014-05-02 15:26:25 -0700642 return NO_ERROR;
643}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700644
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800645status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700646 DisplayStatInfo* stats) {
647 if (stats == NULL) {
648 return BAD_VALUE;
649 }
650
651 // FIXME for now we always return stats for the primary display
652 memset(stats, 0, sizeof(*stats));
653 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
654 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
655 return NO_ERROR;
656}
657
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700658int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700659 sp<DisplayDevice> device(getDisplayDevice(display));
660 if (device != NULL) {
661 return device->getActiveConfig();
662 }
663 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700664}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700665
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700666void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
667 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
668 this);
669 int32_t type = hw->getDisplayType();
670 int currentMode = hw->getActiveConfig();
671
672 if (mode == currentMode) {
673 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
674 return;
675 }
676
677 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
678 ALOGW("Trying to set config for virtual display");
679 return;
680 }
681
682 hw->setActiveConfig(mode);
683 getHwComposer().setActiveConfig(type, mode);
684}
685
686status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
687 class MessageSetActiveConfig: public MessageBase {
688 SurfaceFlinger& mFlinger;
689 sp<IBinder> mDisplay;
690 int mMode;
691 public:
692 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
693 int mode) :
694 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
695 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700696 Vector<DisplayInfo> configs;
697 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700698 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700699 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700700 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700701 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700702 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700703 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
704 if (hw == NULL) {
705 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700706 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700707 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
708 ALOGW("Attempt to set active config = %d for virtual display",
709 mMode);
710 } else {
711 mFlinger.setActiveConfigInternal(hw, mMode);
712 }
713 return true;
714 }
715 };
716 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
717 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700718 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700719}
Michael Wright28f24d02016-07-12 13:30:53 -0700720status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
721 Vector<android_color_mode_t>* outColorModes) {
722 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
723 return BAD_VALUE;
724 }
725
726 if (!display.get()) {
727 return NAME_NOT_FOUND;
728 }
729
730 int32_t type = NAME_NOT_FOUND;
731 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
732 if (display == mBuiltinDisplays[i]) {
733 type = i;
734 break;
735 }
736 }
737
738 if (type < 0) {
739 return type;
740 }
741
742 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
743 outColorModes->clear();
744 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
745
746 return NO_ERROR;
747}
748
749android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
750 sp<DisplayDevice> device(getDisplayDevice(display));
751 if (device != nullptr) {
752 return device->getActiveColorMode();
753 }
754 return static_cast<android_color_mode_t>(BAD_VALUE);
755}
756
757void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
758 android_color_mode_t mode) {
759 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
760 this);
761 int32_t type = hw->getDisplayType();
762 android_color_mode_t currentMode = hw->getActiveColorMode();
763
764 if (mode == currentMode) {
765 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
766 return;
767 }
768
769 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
770 ALOGW("Trying to set config for virtual display");
771 return;
772 }
773
774 hw->setActiveColorMode(mode);
775 getHwComposer().setActiveColorMode(type, mode);
776}
777
778
779status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
780 android_color_mode_t colorMode) {
781 class MessageSetActiveColorMode: public MessageBase {
782 SurfaceFlinger& mFlinger;
783 sp<IBinder> mDisplay;
784 android_color_mode_t mMode;
785 public:
786 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
787 android_color_mode_t mode) :
788 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
789 virtual bool handler() {
790 Vector<android_color_mode_t> modes;
791 mFlinger.getDisplayColorModes(mDisplay, &modes);
792 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
793 if (mMode < 0 || !exists) {
794 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
795 mDisplay.get());
796 return true;
797 }
798 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
799 if (hw == nullptr) {
800 ALOGE("Attempt to set active color mode = %d for null display %p",
801 mMode, mDisplay.get());
802 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
803 ALOGW("Attempt to set active color mode= %d for virtual display",
804 mMode);
805 } else {
806 mFlinger.setActiveColorModeInternal(hw, mMode);
807 }
808 return true;
809 }
810 };
811 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
812 postMessageSync(msg);
813 return NO_ERROR;
814}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700815
Svetoslavd85084b2014-03-20 10:28:31 -0700816status_t SurfaceFlinger::clearAnimationFrameStats() {
817 Mutex::Autolock _l(mStateLock);
818 mAnimFrameTracker.clearStats();
819 return NO_ERROR;
820}
821
822status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
823 Mutex::Autolock _l(mStateLock);
824 mAnimFrameTracker.getStats(outStats);
825 return NO_ERROR;
826}
827
Dan Stozac4f471e2016-03-24 09:31:08 -0700828status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
829 HdrCapabilities* outCapabilities) const {
830 Mutex::Autolock _l(mStateLock);
831
832 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
833 if (displayDevice == nullptr) {
834 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
835 return BAD_VALUE;
836 }
837
838 std::unique_ptr<HdrCapabilities> capabilities =
839 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
840 if (capabilities) {
841 std::swap(*outCapabilities, *capabilities);
842 } else {
843 return BAD_VALUE;
844 }
845
846 return NO_ERROR;
847}
848
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800849// ----------------------------------------------------------------------------
850
851sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800852 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700853}
854
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800856
857void SurfaceFlinger::waitForEvent() {
858 mEventQueue.waitMessage();
859}
860
861void SurfaceFlinger::signalTransaction() {
862 mEventQueue.invalidate();
863}
864
865void SurfaceFlinger::signalLayerUpdate() {
866 mEventQueue.invalidate();
867}
868
869void SurfaceFlinger::signalRefresh() {
870 mEventQueue.refresh();
871}
872
873status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800874 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800875 return mEventQueue.postMessage(msg, reltime);
876}
877
878status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800879 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800880 status_t res = mEventQueue.postMessage(msg, reltime);
881 if (res == NO_ERROR) {
882 msg->wait();
883 }
884 return res;
885}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800886
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700887void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700888 do {
889 waitForEvent();
890 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800891}
892
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700893void SurfaceFlinger::enableHardwareVsync() {
894 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700895 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700896 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700897 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
898 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700899 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700900 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700901}
902
Jesse Hall948fe0c2013-10-14 12:56:09 -0700903void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700904 Mutex::Autolock _l(mHWVsyncLock);
905
Jesse Hall948fe0c2013-10-14 12:56:09 -0700906 if (makeAvailable) {
907 mHWVsyncAvailable = true;
908 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700909 // Hardware vsync is not currently available, so abort the resync
910 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700911 return;
912 }
913
Dan Stoza9e56aa02015-11-02 13:00:03 -0800914 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
915 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700916
917 mPrimaryDispSync.reset();
918 mPrimaryDispSync.setPeriod(period);
919
920 if (!mPrimaryHWVsyncEnabled) {
921 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700922 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
923 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700924 mPrimaryHWVsyncEnabled = true;
925 }
926}
927
Jesse Hall948fe0c2013-10-14 12:56:09 -0700928void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700929 Mutex::Autolock _l(mHWVsyncLock);
930 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700931 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
932 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700933 mPrimaryDispSync.endResync();
934 mPrimaryHWVsyncEnabled = false;
935 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700936 if (makeUnavailable) {
937 mHWVsyncAvailable = false;
938 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700939}
940
Tim Murray4a4e4a22016-04-19 16:29:23 +0000941void SurfaceFlinger::resyncWithRateLimit() {
942 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
943 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700944 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000945 }
946}
947
Dan Stoza9e56aa02015-11-02 13:00:03 -0800948void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700949 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700950
Jamie Gennisd1700752013-10-14 12:22:52 -0700951 { // Scope for the lock
952 Mutex::Autolock _l(mHWVsyncLock);
953 if (type == 0 && mPrimaryHWVsyncEnabled) {
954 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700955 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700956 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700957
958 if (needsHwVsync) {
959 enableHardwareVsync();
960 } else {
961 disableHardwareVsync(false);
962 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700963}
964
Dan Stoza9e56aa02015-11-02 13:00:03 -0800965void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
966 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
967 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
968 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700969
Dan Stoza9e56aa02015-11-02 13:00:03 -0800970 // All non-virtual displays are currently considered secure.
971 bool isSecure = true;
972
973 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
974 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
975 wp<IBinder> token = mBuiltinDisplays[type];
976
977 sp<IGraphicBufferProducer> producer;
978 sp<IGraphicBufferConsumer> consumer;
979 BufferQueue::createBufferQueue(&producer, &consumer,
980 new GraphicBufferAlloc());
981
982 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
983 DisplayDevice::DISPLAY_PRIMARY, consumer);
984 sp<DisplayDevice> hw = new DisplayDevice(this,
985 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
986 producer, mRenderEngine->getEGLConfig());
987 mDisplays.add(token, hw);
988 } else {
989 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700990 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800991 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800992 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700993 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800994 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
995 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700996 }
997 setTransactionFlags(eDisplayTransactionNeeded);
998
Andy McFadden9e9689c2012-10-10 18:17:51 -0700999 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001000 }
Mathias Agopian86303202012-07-24 22:46:10 -07001001}
1002
Dan Stoza9e56aa02015-11-02 13:00:03 -08001003void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001004 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001005 getHwComposer().setVsyncEnabled(disp,
1006 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001007}
1008
Mathias Agopian4fec8732012-06-29 14:12:52 -07001009void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001010 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001011 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001012 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001013 bool frameMissed = !mHadClientComposition &&
1014 mPreviousPresentFence != Fence::NO_FENCE &&
1015 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1016 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001017 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001018 signalLayerUpdate();
1019 break;
1020 }
1021
Dan Stoza6b9454d2014-11-07 16:00:59 -08001022 bool refreshNeeded = handleMessageTransaction();
1023 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001024 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001025 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001026 // Signal a refresh if a transaction modified the window state,
1027 // a new buffer was latched, or if HWC has requested a full
1028 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001029 signalRefresh();
1030 }
1031 break;
1032 }
1033 case MessageQueue::REFRESH: {
1034 handleMessageRefresh();
1035 break;
1036 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001037 }
1038}
1039
Dan Stoza6b9454d2014-11-07 16:00:59 -08001040bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001041 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001042 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001043 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001044 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001045 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001046 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001047}
1048
Dan Stoza6b9454d2014-11-07 16:00:59 -08001049bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001050 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001051 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001052}
1053
1054void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001055 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001056
Pablo Ceballos40845df2016-01-25 17:41:15 -08001057 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001058
Dan Stoza05dacfb2016-07-01 13:33:38 -07001059 preComposition();
1060 rebuildLayerStacks();
1061 setUpHWComposer();
1062 doDebugFlashRegions();
1063 doComposition();
1064 postComposition(refreshStartTime);
1065
1066 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001067
1068 mHadClientComposition = false;
1069 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1070 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1071 mHadClientComposition = mHadClientComposition ||
1072 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1073 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001074
Dan Stoza9e56aa02015-11-02 13:00:03 -08001075 // Release any buffers which were replaced this frame
1076 for (auto& layer : mLayersWithQueuedFrames) {
1077 layer->releasePendingBuffer();
1078 }
1079 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001080}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001081
Mathias Agopiancd60f992012-08-16 16:28:27 -07001082void SurfaceFlinger::doDebugFlashRegions()
1083{
1084 // is debugging enabled
1085 if (CC_LIKELY(!mDebugRegion))
1086 return;
1087
1088 const bool repaintEverything = mRepaintEverything;
1089 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1090 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001091 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001092 // transform the dirty region into this screen's coordinate space
1093 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1094 if (!dirtyRegion.isEmpty()) {
1095 // redraw the whole screen
1096 doComposeSurfaces(hw, Region(hw->bounds()));
1097
1098 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001099 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001100 RenderEngine& engine(getRenderEngine());
1101 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1102
Mathias Agopianda27af92012-09-13 18:17:13 -07001103 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001104 }
1105 }
1106 }
1107
1108 postFramebuffer();
1109
1110 if (mDebugRegion > 1) {
1111 usleep(mDebugRegion * 1000);
1112 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001113
Dan Stoza9e56aa02015-11-02 13:00:03 -08001114 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001115 auto& displayDevice = mDisplays[displayId];
1116 if (!displayDevice->isDisplayOn()) {
1117 continue;
1118 }
1119
1120 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001121 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1122 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001123 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001124}
1125
1126void SurfaceFlinger::preComposition()
1127{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128 ATRACE_CALL();
1129 ALOGV("preComposition");
1130
Mathias Agopiancd60f992012-08-16 16:28:27 -07001131 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001132 const LayerVector& layers(mDrawingState.layersSortedByZ);
1133 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001134 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001135 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001136 needExtraInvalidate = true;
1137 }
1138 }
1139 if (needExtraInvalidate) {
1140 signalLayerUpdate();
1141 }
1142}
1143
Pablo Ceballos40845df2016-01-25 17:41:15 -08001144void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001145{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001146 ATRACE_CALL();
1147 ALOGV("postComposition");
1148
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001149 const LayerVector& layers(mDrawingState.layersSortedByZ);
1150 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001151 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001152 bool frameLatched = layers[i]->onPostComposition();
1153 if (frameLatched) {
1154 recordBufferingStats(layers[i]->getName().string(),
1155 layers[i]->getOccupancyHistory(false));
1156 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001157 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001158
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001160
1161 if (presentFence->isValid()) {
1162 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1163 enableHardwareVsync();
1164 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001165 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001166 }
1167 }
1168
Dan Stozab90cf072015-03-05 11:05:59 -08001169 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001170 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001171 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001172 enableHardwareVsync();
1173 }
1174 }
1175
Pablo Ceballos40845df2016-01-25 17:41:15 -08001176 mFenceTracker.addFrame(refreshStartTime, presentFence,
1177 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1178
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001179 if (mAnimCompositionPending) {
1180 mAnimCompositionPending = false;
1181
Jesse Halla9a1b002013-02-27 16:39:25 -08001182 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001183 mAnimFrameTracker.setActualPresentFence(presentFence);
1184 } else {
1185 // The HWC doesn't support present fences, so use the refresh
1186 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187 nsecs_t presentTime =
1188 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001189 mAnimFrameTracker.setActualPresentTime(presentTime);
1190 }
1191 mAnimFrameTracker.advanceFrame();
1192 }
Dan Stozab90cf072015-03-05 11:05:59 -08001193
1194 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1195 return;
1196 }
1197
1198 nsecs_t currentTime = systemTime();
1199 if (mHasPoweredOff) {
1200 mHasPoweredOff = false;
1201 } else {
1202 nsecs_t period = mPrimaryDispSync.getPeriod();
1203 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1204 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1205 if (numPeriods < NUM_BUCKETS - 1) {
1206 mFrameBuckets[numPeriods] += elapsedTime;
1207 } else {
1208 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1209 }
1210 mTotalTime += elapsedTime;
1211 }
1212 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001213}
1214
1215void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 ATRACE_CALL();
1217 ALOGV("rebuildLayerStacks");
1218
Mathias Agopiancd60f992012-08-16 16:28:27 -07001219 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001220 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001221 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001222 mVisibleRegionsDirty = false;
1223 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001224
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001225 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001226 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001227 Region opaqueRegion;
1228 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001229 Vector<sp<Layer>> layersSortedByZ;
1230 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1231 const Transform& tr(displayDevice->getTransform());
1232 const Rect bounds(displayDevice->getBounds());
1233 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001234 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001235 displayDevice->getLayerStack(), dirtyRegion,
1236 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001237
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001238 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001239 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001240 const sp<Layer>& layer(layers[i]);
1241 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001242 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001243 Region drawRegion(tr.transform(
1244 layer->visibleNonTransparentRegion));
1245 drawRegion.andSelf(bounds);
1246 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001247 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001248 } else {
1249 // Clear out the HWC layer if this layer was
1250 // previously visible, but no longer is
1251 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1252 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001253 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001254 }
1255 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001256 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001257 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1258 displayDevice->undefinedRegion.set(bounds);
1259 displayDevice->undefinedRegion.subtractSelf(
1260 tr.transform(opaqueRegion));
1261 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001262 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001263 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001264}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001265
Mathias Agopiancd60f992012-08-16 16:28:27 -07001266void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001267 ATRACE_CALL();
1268 ALOGV("setUpHWComposer");
1269
Jesse Hall028dc8f2013-08-20 16:35:32 -07001270 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001271 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1272 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1273 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1274
1275 // If nothing has changed (!dirty), don't recompose.
1276 // If something changed, but we don't currently have any visible layers,
1277 // and didn't when we last did a composition, then skip it this time.
1278 // The second rule does two things:
1279 // - When all layers are removed from a display, we'll emit one black
1280 // frame, then nothing more until we get new layers.
1281 // - When a display is created with a private layer stack, we won't
1282 // emit any black frames until a layer is added to the layer stack.
1283 bool mustRecompose = dirty && !(empty && wasEmpty);
1284
1285 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1286 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1287 mustRecompose ? "doing" : "skipping",
1288 dirty ? "+" : "-",
1289 empty ? "+" : "-",
1290 wasEmpty ? "+" : "-");
1291
Dan Stoza71433162014-02-04 16:22:36 -08001292 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001293
1294 if (mustRecompose) {
1295 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1296 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001297 }
1298
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 // build the h/w work list
1300 if (CC_UNLIKELY(mGeometryInvalid)) {
1301 mGeometryInvalid = false;
1302 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1303 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1304 const auto hwcId = displayDevice->getHwcDisplayId();
1305 if (hwcId >= 0) {
1306 const Vector<sp<Layer>>& currentLayers(
1307 displayDevice->getVisibleLayersSortedByZ());
1308 bool foundLayerWithoutHwc = false;
1309 for (auto& layer : currentLayers) {
1310 if (!layer->hasHwcLayer(hwcId)) {
1311 auto hwcLayer = mHwc->createLayer(hwcId);
1312 if (hwcLayer) {
1313 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1314 } else {
1315 layer->forceClientComposition(hwcId);
1316 foundLayerWithoutHwc = true;
1317 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001318 }
1319 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001320
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001322 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001323 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001324 }
1325 }
1326 }
1327 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001328 }
Riley Andrews03414a12014-07-01 14:22:59 -07001329
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001330
1331 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1332
Dan Stoza9e56aa02015-11-02 13:00:03 -08001333 // Set the per-frame data
1334 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1335 auto& displayDevice = mDisplays[displayId];
1336 const auto hwcId = displayDevice->getHwcDisplayId();
1337 if (hwcId < 0) {
1338 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001339 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001340 if (colorMatrix != mPreviousColorMatrix) {
1341 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1342 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1343 "display %zd: %d", displayId, result);
1344 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001345 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1346 layer->setPerFrameData(displayDevice);
1347 }
1348 }
1349
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001350 mPreviousColorMatrix = colorMatrix;
1351
Dan Stoza9e56aa02015-11-02 13:00:03 -08001352 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001353 auto& displayDevice = mDisplays[displayId];
1354 if (!displayDevice->isDisplayOn()) {
1355 continue;
1356 }
1357
1358 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001359 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1360 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001361 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001362}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001363
Mathias Agopiancd60f992012-08-16 16:28:27 -07001364void SurfaceFlinger::doComposition() {
1365 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001366 ALOGV("doComposition");
1367
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001368 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001369 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001370 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001371 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001372 // transform the dirty region into this screen's coordinate space
1373 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001374
1375 // repaint the framebuffer (if needed)
1376 doDisplayComposition(hw, dirtyRegion);
1377
Mathias Agopiancd60f992012-08-16 16:28:27 -07001378 hw->dirtyRegion.clear();
1379 hw->flip(hw->swapRegion);
1380 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001381 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001382 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001383 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001384}
1385
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001386void SurfaceFlinger::postFramebuffer()
1387{
Mathias Agopian841cde52012-03-01 15:44:37 -08001388 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001389 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001390
Mathias Agopiana44b0412011-10-16 18:46:35 -07001391 const nsecs_t now = systemTime();
1392 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001393
Dan Stoza9e56aa02015-11-02 13:00:03 -08001394 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1395 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001396 if (!displayDevice->isDisplayOn()) {
1397 continue;
1398 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001399 const auto hwcId = displayDevice->getHwcDisplayId();
1400 if (hwcId >= 0) {
1401 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001402 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001403 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001404 if (displayId == 0) {
1405 // Make the default display current because the VirtualDisplayDevice
1406 // code cannot deal with dequeueBuffer() being called outside of the
1407 // composition loop; however the code below can call glFlush() which
1408 // is allowed to (and does in some case) call dequeueBuffer().
1409 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1410 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001411 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1412 sp<Fence> releaseFence = Fence::NO_FENCE;
1413 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1414 releaseFence = displayDevice->getClientTargetAcquireFence();
1415 } else {
1416 auto hwcLayer = layer->getHwcLayer(hwcId);
1417 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001418 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001419 layer->onLayerDisplayed(releaseFence);
1420 }
1421 if (hwcId >= 0) {
1422 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001423 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001424 }
1425
Mathias Agopiana44b0412011-10-16 18:46:35 -07001426 mLastSwapBufferTime = systemTime() - now;
1427 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001428
1429 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1430 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1431 logFrameStats();
1432 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001433}
1434
Mathias Agopian87baae12012-07-31 12:38:26 -07001435void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001436{
Mathias Agopian841cde52012-03-01 15:44:37 -08001437 ATRACE_CALL();
1438
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001439 // here we keep a copy of the drawing state (that is the state that's
1440 // going to be overwritten by handleTransactionLocked()) outside of
1441 // mStateLock so that the side-effects of the State assignment
1442 // don't happen with mStateLock held (which can cause deadlocks).
1443 State drawingState(mDrawingState);
1444
Mathias Agopianca4d3602011-05-19 15:38:14 -07001445 Mutex::Autolock _l(mStateLock);
1446 const nsecs_t now = systemTime();
1447 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001448
Mathias Agopianca4d3602011-05-19 15:38:14 -07001449 // Here we're guaranteed that some transaction flags are set
1450 // so we can call handleTransactionLocked() unconditionally.
1451 // We call getTransactionFlags(), which will also clear the flags,
1452 // with mStateLock held to guarantee that mCurrentState won't change
1453 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001454
Mathias Agopiane57f2922012-08-09 16:29:12 -07001455 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001456 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001457
Mathias Agopianca4d3602011-05-19 15:38:14 -07001458 mLastTransactionTime = systemTime() - now;
1459 mDebugInTransaction = 0;
1460 invalidateHwcGeometry();
1461 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001462}
1463
Mathias Agopian87baae12012-07-31 12:38:26 -07001464void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001465{
1466 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001467 const size_t count = currentLayers.size();
1468
Dan Stoza7dde5992015-05-22 09:51:44 -07001469 // Notify all layers of available frames
1470 for (size_t i = 0; i < count; ++i) {
1471 currentLayers[i]->notifyAvailableFrames();
1472 }
1473
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001474 /*
1475 * Traversal of the children
1476 * (perform the transaction for each of them if needed)
1477 */
1478
Mathias Agopian3559b072012-08-15 13:46:03 -07001479 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001481 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001482 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1483 if (!trFlags) continue;
1484
1485 const uint32_t flags = layer->doTransaction(0);
1486 if (flags & Layer::eVisibleRegion)
1487 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488 }
1489 }
1490
1491 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001492 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 */
1494
Mathias Agopiane57f2922012-08-09 16:29:12 -07001495 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001496 // here we take advantage of Vector's copy-on-write semantics to
1497 // improve performance by skipping the transaction entirely when
1498 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001499 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1500 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001501 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001502 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001503 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001504 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001505
1506 // find the displays that were removed
1507 // (ie: in drawing state but not in current state)
1508 // also handle displays that changed
1509 // (ie: displays that are in both lists)
1510 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001511 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1512 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001513 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001514 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001515 // Call makeCurrent() on the primary display so we can
1516 // be sure that nothing associated with this display
1517 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001518 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001519 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001520 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1521 if (hw != NULL)
1522 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001523 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001524 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001525 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001526 } else {
1527 ALOGW("trying to remove the main display");
1528 }
1529 } else {
1530 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001531 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001532 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001533 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1534 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001535 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001536 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001537 // recreating the DisplayDevice, so we just remove it
1538 // from the drawing state, so that it get re-added
1539 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001540 sp<DisplayDevice> hw(getDisplayDevice(display));
1541 if (hw != NULL)
1542 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001543 mDisplays.removeItem(display);
1544 mDrawingState.displays.removeItemsAt(i);
1545 dc--; i--;
1546 // at this point we must loop to the next item
1547 continue;
1548 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001549
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001550 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001551 if (disp != NULL) {
1552 if (state.layerStack != draw[i].layerStack) {
1553 disp->setLayerStack(state.layerStack);
1554 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001555 if ((state.orientation != draw[i].orientation)
1556 || (state.viewport != draw[i].viewport)
1557 || (state.frame != draw[i].frame))
1558 {
1559 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001560 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001561 }
Michael Lentine47e45402014-07-18 15:34:25 -07001562 if (state.width != draw[i].width || state.height != draw[i].height) {
1563 disp->setDisplaySize(state.width, state.height);
1564 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001565 }
1566 }
1567 }
1568
1569 // find displays that were added
1570 // (ie: in current state but not in drawing state)
1571 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001572 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001573 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001574
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001575 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001576 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001577 sp<IGraphicBufferProducer> bqProducer;
1578 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001579 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1580 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001581
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001583 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001584 // Virtual displays without a surface are dormant:
1585 // they have external state (layer stack, projection,
1586 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001587 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001588
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001589 if (mUseHwcVirtualDisplays) {
1590 int width = 0;
1591 int status = state.surface->query(
1592 NATIVE_WINDOW_WIDTH, &width);
1593 ALOGE_IF(status != NO_ERROR,
1594 "Unable to query width (%d)", status);
1595 int height = 0;
1596 status = state.surface->query(
1597 NATIVE_WINDOW_HEIGHT, &height);
1598 ALOGE_IF(status != NO_ERROR,
1599 "Unable to query height (%d)", status);
1600 int intFormat = 0;
1601 status = state.surface->query(
1602 NATIVE_WINDOW_FORMAT, &intFormat);
1603 ALOGE_IF(status != NO_ERROR,
1604 "Unable to query format (%d)", status);
1605 auto format = static_cast<android_pixel_format_t>(
1606 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001607
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001608 mHwc->allocateVirtualDisplay(width, height, &format,
1609 &hwcId);
1610 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001611
Dan Stoza5cf424b2016-05-20 14:02:39 -07001612 // TODO: Plumb requested format back up to consumer
1613
Dan Stoza9e56aa02015-11-02 13:00:03 -08001614 sp<VirtualDisplaySurface> vds =
1615 new VirtualDisplaySurface(*mHwc,
1616 hwcId, state.surface, bqProducer,
1617 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001618
1619 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001620 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001621 }
1622 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001623 ALOGE_IF(state.surface!=NULL,
1624 "adding a supported display, but rendering "
1625 "surface is provided (%p), ignoring it",
1626 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1628 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1629 dispSurface = new FramebufferSurface(*mHwc,
1630 DisplayDevice::DISPLAY_EXTERNAL,
1631 bqConsumer);
1632 producer = bqProducer;
1633 } else {
1634 ALOGE("Attempted to add non-external non-virtual"
1635 " display");
1636 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001637 }
1638
1639 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001640 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001641 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 state.type, hwcId, state.isSecure, display,
1643 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001644 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001645 hw->setLayerStack(state.layerStack);
1646 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001647 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001648 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001649 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001651 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001652 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001653 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001654 }
1655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001656 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001658
Mathias Agopian84300952012-11-21 16:02:13 -08001659 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1660 // The transform hint might have changed for some layers
1661 // (either because a display has changed, or because a layer
1662 // as changed).
1663 //
1664 // Walk through all the layers in currentLayers,
1665 // and update their transform hint.
1666 //
1667 // If a layer is visible only on a single display, then that
1668 // display is used to calculate the hint, otherwise we use the
1669 // default display.
1670 //
1671 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1672 // the hint is set before we acquire a buffer from the surface texture.
1673 //
1674 // NOTE: layer transactions have taken place already, so we use their
1675 // drawing state. However, SurfaceFlinger's own transaction has not
1676 // happened yet, so we must use the current state layer list
1677 // (soon to become the drawing state list).
1678 //
1679 sp<const DisplayDevice> disp;
1680 uint32_t currentlayerStack = 0;
1681 for (size_t i=0; i<count; i++) {
1682 // NOTE: we rely on the fact that layers are sorted by
1683 // layerStack first (so we don't have to traverse the list
1684 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001685 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001686 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001687 if (i==0 || currentlayerStack != layerStack) {
1688 currentlayerStack = layerStack;
1689 // figure out if this layerstack is mirrored
1690 // (more than one display) if so, pick the default display,
1691 // if not, pick the only display it's on.
1692 disp.clear();
1693 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1694 sp<const DisplayDevice> hw(mDisplays[dpy]);
1695 if (hw->getLayerStack() == currentlayerStack) {
1696 if (disp == NULL) {
1697 disp = hw;
1698 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001699 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001700 break;
1701 }
1702 }
1703 }
1704 }
Chet Haase91d25932013-04-11 15:24:55 -07001705 if (disp == NULL) {
1706 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1707 // redraw after transform hint changes. See bug 8508397.
1708
1709 // could be null when this layer is using a layerStack
1710 // that is not visible on any display. Also can occur at
1711 // screen off/on times.
1712 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001713 }
Chet Haase91d25932013-04-11 15:24:55 -07001714 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001715 }
1716 }
1717
1718
Mathias Agopian3559b072012-08-15 13:46:03 -07001719 /*
1720 * Perform our own transaction if needed
1721 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001722
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001723 const LayerVector& layers(mDrawingState.layersSortedByZ);
1724 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001725 // layers have been added
1726 mVisibleRegionsDirty = true;
1727 }
1728
1729 // some layers might have been removed, so
1730 // we need to update the regions they're exposing.
1731 if (mLayersRemoved) {
1732 mLayersRemoved = false;
1733 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001734 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001735 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001736 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001737 if (currentLayers.indexOf(layer) < 0) {
1738 // this layer is not visible anymore
1739 // TODO: we could traverse the tree from front to back and
1740 // compute the actual visible region
1741 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001742 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001743 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001744 Region(Rect(s.active.w, s.active.h)));
1745 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001748 }
1749
1750 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001751
1752 updateCursorAsync();
1753}
1754
1755void SurfaceFlinger::updateCursorAsync()
1756{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001757 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1758 auto& displayDevice = mDisplays[displayId];
1759 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001760 continue;
1761 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762
1763 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1764 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001765 }
1766 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001767}
1768
1769void SurfaceFlinger::commitTransaction()
1770{
Steve Pfetsch1d3df542016-09-29 17:16:29 -07001771 sp<const DisplayDevice> hw = getDefaultDisplayDevice();
1772
1773 if (!mLayersPendingRemoval.isEmpty() && hw->isDisplayOn()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001774 // Notify removed layers now that they can't be drawn from
1775 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Steve Pfetsch1d3df542016-09-29 17:16:29 -07001776 mCurrentState.layersSortedByZ.remove(mLayersPendingRemoval[i]);
Dan Stozae77c7662016-05-13 11:37:28 -07001777 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1778 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001779 mLayersPendingRemoval[i]->onRemoved();
1780 }
1781 mLayersPendingRemoval.clear();
1782 }
1783
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001784 // If this transaction is part of a window animation then the next frame
1785 // we composite should be considered an animation as well.
1786 mAnimCompositionPending = mAnimTransactionPending;
1787
Mathias Agopian4fec8732012-06-29 14:12:52 -07001788 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001789 mTransactionPending = false;
1790 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001791 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001792}
1793
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001794void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001795 const LayerVector& currentLayers, uint32_t layerStack,
1796 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797{
Mathias Agopian841cde52012-03-01 15:44:37 -08001798 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001799 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001800
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001801 Region aboveOpaqueLayers;
1802 Region aboveCoveredLayers;
1803 Region dirty;
1804
Mathias Agopian87baae12012-07-31 12:38:26 -07001805 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001806
1807 size_t i = currentLayers.size();
1808 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001809 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810
1811 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001812 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813
Jesse Hall01e29052013-02-19 16:13:35 -08001814 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001815 if (s.layerStack != layerStack)
1816 continue;
1817
Mathias Agopianab028732010-03-16 16:41:46 -07001818 /*
1819 * opaqueRegion: area of a surface that is fully opaque.
1820 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001822
1823 /*
1824 * visibleRegion: area of a surface that is visible on screen
1825 * and not fully transparent. This is essentially the layer's
1826 * footprint minus the opaque regions above it.
1827 * Areas covered by a translucent surface are considered visible.
1828 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001829 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001830
1831 /*
1832 * coveredRegion: area of a surface that is covered by all
1833 * visible regions above it (which includes the translucent areas).
1834 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001835 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001836
Jesse Halla8026d22012-09-25 13:25:04 -07001837 /*
1838 * transparentRegion: area of a surface that is hinted to be completely
1839 * transparent. This is only used to tell when the layer has no visible
1840 * non-transparent regions and can be removed from the layer list. It
1841 * does not affect the visibleRegion of this layer or any layers
1842 * beneath it. The hint may not be correct if apps don't respect the
1843 * SurfaceView restrictions (which, sadly, some don't).
1844 */
1845 Region transparentRegion;
1846
Mathias Agopianab028732010-03-16 16:41:46 -07001847
1848 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001849 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001850 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001851 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001852 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001853 if (!visibleRegion.isEmpty()) {
1854 // Remove the transparent area from the visible region
1855 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001856 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001857 if (tr.preserveRects()) {
1858 // transform the transparent region
1859 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001860 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001861 // transformation too complex, can't do the
1862 // transparent region optimization.
1863 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001864 }
Mathias Agopianab028732010-03-16 16:41:46 -07001865 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866
Mathias Agopianab028732010-03-16 16:41:46 -07001867 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001868 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001870 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1871 // the opaque region is the layer's footprint
1872 opaqueRegion = visibleRegion;
1873 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001874 }
1875 }
1876
Mathias Agopianab028732010-03-16 16:41:46 -07001877 // Clip the covered region to the visible region
1878 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1879
1880 // Update aboveCoveredLayers for next (lower) layer
1881 aboveCoveredLayers.orSelf(visibleRegion);
1882
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001883 // subtract the opaque region covered by the layers above us
1884 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885
1886 // compute this layer's dirty region
1887 if (layer->contentDirty) {
1888 // we need to invalidate the whole region
1889 dirty = visibleRegion;
1890 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001891 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001892 layer->contentDirty = false;
1893 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001894 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001895 * the exposed region consists of two components:
1896 * 1) what's VISIBLE now and was COVERED before
1897 * 2) what's EXPOSED now less what was EXPOSED before
1898 *
1899 * note that (1) is conservative, we start with the whole
1900 * visible region but only keep what used to be covered by
1901 * something -- which mean it may have been exposed.
1902 *
1903 * (2) handles areas that were not covered by anything but got
1904 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001905 */
Mathias Agopianab028732010-03-16 16:41:46 -07001906 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001907 const Region oldVisibleRegion = layer->visibleRegion;
1908 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001909 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1910 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911 }
1912 dirty.subtractSelf(aboveOpaqueLayers);
1913
1914 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001915 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001916
Mathias Agopianab028732010-03-16 16:41:46 -07001917 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001919
Jesse Halla8026d22012-09-25 13:25:04 -07001920 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001921 layer->setVisibleRegion(visibleRegion);
1922 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001923 layer->setVisibleNonTransparentRegion(
1924 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001925 }
1926
Mathias Agopian87baae12012-07-31 12:38:26 -07001927 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001928}
1929
Mathias Agopian87baae12012-07-31 12:38:26 -07001930void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1931 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001932 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001933 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1934 if (hw->getLayerStack() == layerStack) {
1935 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001936 }
1937 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001938}
1939
Dan Stoza6b9454d2014-11-07 16:00:59 -08001940bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001941{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 ALOGV("handlePageFlip");
1943
Mathias Agopian4fec8732012-06-29 14:12:52 -07001944 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001945
Mathias Agopian4fec8732012-06-29 14:12:52 -07001946 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001947 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001948 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001949
1950 // Store the set of layers that need updates. This set must not change as
1951 // buffers are being latched, as this could result in a deadlock.
1952 // Example: Two producers share the same command stream and:
1953 // 1.) Layer 0 is latched
1954 // 2.) Layer 0 gets a new frame
1955 // 2.) Layer 1 gets a new frame
1956 // 3.) Layer 1 is latched.
1957 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1958 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001959 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001960 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001961 if (layer->hasQueuedFrame()) {
1962 frameQueued = true;
1963 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001965 } else {
1966 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001967 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001968 } else {
1969 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001970 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001971 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001973 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001974 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001975 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001976 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001977 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001978
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001979 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001980
1981 // If we will need to wake up at some time in the future to deal with a
1982 // queued frame that shouldn't be displayed during this vsync period, wake
1983 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001984 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001985 signalLayerUpdate();
1986 }
1987
1988 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990}
1991
Mathias Agopianad456f92011-01-13 17:53:01 -08001992void SurfaceFlinger::invalidateHwcGeometry()
1993{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001995}
1996
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001997
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001999 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000{
Dan Stoza71433162014-02-04 16:22:36 -08002001 // We only need to actually compose the display if:
2002 // 1) It is being handled by hardware composer, which may need this to
2003 // keep its virtual display state machine in sync, or
2004 // 2) There is work to be done (the dirty region isn't empty)
2005 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2006 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002008 return;
2009 }
2010
Dan Stoza9e56aa02015-11-02 13:00:03 -08002011 ALOGV("doDisplayComposition");
2012
Mathias Agopian87baae12012-07-31 12:38:26 -07002013 Region dirtyRegion(inDirtyRegion);
2014
Mathias Agopianb8a55602009-06-26 19:06:36 -07002015 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002016 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002017
Mathias Agopian42977342012-08-05 00:40:46 -07002018 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002019 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002020 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2021 // takes a rectangle, we must make sure to update that whole
2022 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002023 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002024 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002025 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002026 // We need to redraw the rectangle that will be updated
2027 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002028 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002029 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002030 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002031 } else {
2032 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002033 dirtyRegion.set(hw->bounds());
2034 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035 }
2036 }
2037
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002038 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002039
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002040 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002041 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002042
2043 // swap buffers (presentation)
2044 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045}
2046
Dan Stoza9e56aa02015-11-02 13:00:03 -08002047bool SurfaceFlinger::doComposeSurfaces(
2048 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002049{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002051
Dan Stoza9e56aa02015-11-02 13:00:03 -08002052 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002053
2054 mat4 oldColorMatrix;
2055 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2056 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2057 if (applyColorMatrix) {
2058 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2059 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2060 }
2061
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2063 if (hasClientComposition) {
2064 ALOGV("hasClientComposition");
2065
2066 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002067 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002069 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2070 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2071 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2072 }
2073 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002074 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002075
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2078 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002079 // when using overlays, we assume a fully transparent framebuffer
2080 // NOTE: we could reduce how much we need to clear, for instance
2081 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002082 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002083 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002085 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002086 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002088
2089 // we remove the scissor part
2090 // we're left with the letterbox region
2091 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002093
2094 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002095 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002096
2097 // but limit it to the dirty region
2098 region.andSelf(dirty);
2099
Mathias Agopianb9494d52012-04-18 02:28:45 -07002100 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002101 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002102 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002104 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002105 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002106
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002108 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002109 // scissor on the main display. It should never be needed
2110 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111 const Rect& bounds(displayDevice->getBounds());
2112 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002113 if (scissor != bounds) {
2114 // scissor doesn't match the screen's dimensions, so we
2115 // need to clear everything outside of it and enable
2116 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002117
Mathias Agopianf45c5102012-10-24 16:29:17 -07002118 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002119 const uint32_t height = displayDevice->getHeight();
2120 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002121 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002122 }
2123 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002124 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002125
Mathias Agopian85d751c2012-08-29 16:59:24 -07002126 /*
2127 * and then, render the layers targeted at the framebuffer
2128 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002129
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 ALOGV("Rendering client layers");
2131 const Transform& displayTransform = displayDevice->getTransform();
2132 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002133 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002134 bool firstLayer = true;
2135 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2136 const Region clip(dirty.intersect(
2137 displayTransform.transform(layer->visibleRegion)));
2138 ALOGV("Layer: %s", layer->getName().string());
2139 ALOGV(" Composition type: %s",
2140 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002141 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 switch (layer->getCompositionType(hwcId)) {
2143 case HWC2::Composition::Cursor:
2144 case HWC2::Composition::Device:
2145 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002146 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2148 layer->isOpaque(state) && (state.alpha == 1.0f)
2149 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002150 // never clear the very first layer since we're
2151 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002153 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002154 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 case HWC2::Composition::Client: {
2157 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002158 break;
2159 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002160 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002161 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002162 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 } else {
2164 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002165 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002167 }
2168 } else {
2169 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002171 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002173 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002175 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002176 }
2177 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002178
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002179 if (applyColorMatrix) {
2180 getRenderEngine().setupColorTransform(oldColorMatrix);
2181 }
2182
Mathias Agopianf45c5102012-10-24 16:29:17 -07002183 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002185 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002186}
2187
Mathias Agopian3f844832013-08-07 21:24:32 -07002188void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002189 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002190 RenderEngine& engine(getRenderEngine());
2191 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002192}
2193
Dan Stoza7d89d062015-04-30 13:29:25 -07002194status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002195 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002196 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002197 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002198{
Dan Stoza7d89d062015-04-30 13:29:25 -07002199 // add this layer to the current state list
2200 {
2201 Mutex::Autolock _l(mStateLock);
2202 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2203 return NO_MEMORY;
2204 }
2205 mCurrentState.layersSortedByZ.add(lbc);
2206 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2207 }
2208
Mathias Agopian96f08192010-06-02 23:28:45 -07002209 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002210 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002211
Dan Stoza7d89d062015-04-30 13:29:25 -07002212 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002213}
2214
Dan Stoza92cd24e2016-08-09 13:21:03 -07002215status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002216 Mutex::Autolock _l(mStateLock);
Dan Stoza92cd24e2016-08-09 13:21:03 -07002217 sp<Layer> layer = weakLayer.promote();
2218 if (layer == nullptr) {
2219 // The layer has already been removed, carry on
2220 return NO_ERROR;
2221 }
2222
Steve Pfetsch1d3df542016-09-29 17:16:29 -07002223 mLayersPendingRemoval.push(layer);
2224 mLayersRemoved = true;
2225 setTransactionFlags(eTransactionNeeded);
2226 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002227}
2228
Dan Stozac7014012014-02-14 15:03:43 -08002229uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002230 return android_atomic_release_load(&mTransactionFlags);
2231}
2232
Mathias Agopian3f844832013-08-07 21:24:32 -07002233uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2235}
2236
Mathias Agopian3f844832013-08-07 21:24:32 -07002237uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2239 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002240 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241 }
2242 return old;
2243}
2244
Mathias Agopian8b33f032012-07-24 20:43:54 -07002245void SurfaceFlinger::setTransactionState(
2246 const Vector<ComposerState>& state,
2247 const Vector<DisplayState>& displays,
2248 uint32_t flags)
2249{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002250 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002251 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002252 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002253
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002254 if (flags & eAnimation) {
2255 // For window updates that are part of an animation we must wait for
2256 // previous animation "frames" to be handled.
2257 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002258 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002259 if (CC_UNLIKELY(err != NO_ERROR)) {
2260 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002261 // caller after a few seconds.
2262 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2263 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002264 mAnimTransactionPending = false;
2265 break;
2266 }
2267 }
2268 }
2269
Mathias Agopiane57f2922012-08-09 16:29:12 -07002270 size_t count = displays.size();
2271 for (size_t i=0 ; i<count ; i++) {
2272 const DisplayState& s(displays[i]);
2273 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002274 }
2275
Mathias Agopiane57f2922012-08-09 16:29:12 -07002276 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002277 for (size_t i=0 ; i<count ; i++) {
2278 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002279 // Here we need to check that the interface we're given is indeed
2280 // one of our own. A malicious client could give us a NULL
2281 // IInterface, or one of its own or even one of our own but a
2282 // different type. All these situations would cause us to crash.
2283 //
2284 // NOTE: it would be better to use RTTI as we could directly check
2285 // that we have a Client*. however, RTTI is disabled in Android.
2286 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002287 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002288 if (binder != NULL) {
2289 String16 desc(binder->getInterfaceDescriptor());
2290 if (desc == ISurfaceComposerClient::descriptor) {
2291 sp<Client> client( static_cast<Client *>(s.client.get()) );
2292 transactionFlags |= setClientStateLocked(client, s.state);
2293 }
2294 }
2295 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002296 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002297
Robert Carr2a7dbb42016-05-24 11:41:28 -07002298 // If a synchronous transaction is explicitly requested without any changes,
2299 // force a transaction anyway. This can be used as a flush mechanism for
2300 // previous async transactions.
2301 if (transactionFlags == 0 && (flags & eSynchronous)) {
2302 transactionFlags = eTransactionNeeded;
2303 }
2304
Mathias Agopian386aa982011-11-07 21:58:03 -08002305 if (transactionFlags) {
2306 // this triggers the transaction
2307 setTransactionFlags(transactionFlags);
2308
2309 // if this is a synchronous transaction, wait for it to take effect
2310 // before returning.
2311 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002312 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002313 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002314 if (flags & eAnimation) {
2315 mAnimTransactionPending = true;
2316 }
2317 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2319 if (CC_UNLIKELY(err != NO_ERROR)) {
2320 // just in case something goes wrong in SF, return to the
2321 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002322 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2323 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002324 break;
2325 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002326 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 }
2328}
2329
Mathias Agopiane57f2922012-08-09 16:29:12 -07002330uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2331{
Jesse Hall9a143922012-10-04 16:29:19 -07002332 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2333 if (dpyIdx < 0)
2334 return 0;
2335
Mathias Agopiane57f2922012-08-09 16:29:12 -07002336 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002337 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002338 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002339 const uint32_t what = s.what;
2340 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002341 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002342 disp.surface = s.surface;
2343 flags |= eDisplayTransactionNeeded;
2344 }
2345 }
2346 if (what & DisplayState::eLayerStackChanged) {
2347 if (disp.layerStack != s.layerStack) {
2348 disp.layerStack = s.layerStack;
2349 flags |= eDisplayTransactionNeeded;
2350 }
2351 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002352 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002353 if (disp.orientation != s.orientation) {
2354 disp.orientation = s.orientation;
2355 flags |= eDisplayTransactionNeeded;
2356 }
2357 if (disp.frame != s.frame) {
2358 disp.frame = s.frame;
2359 flags |= eDisplayTransactionNeeded;
2360 }
2361 if (disp.viewport != s.viewport) {
2362 disp.viewport = s.viewport;
2363 flags |= eDisplayTransactionNeeded;
2364 }
2365 }
Michael Lentine47e45402014-07-18 15:34:25 -07002366 if (what & DisplayState::eDisplaySizeChanged) {
2367 if (disp.width != s.width) {
2368 disp.width = s.width;
2369 flags |= eDisplayTransactionNeeded;
2370 }
2371 if (disp.height != s.height) {
2372 disp.height = s.height;
2373 flags |= eDisplayTransactionNeeded;
2374 }
2375 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002376 }
2377 return flags;
2378}
2379
2380uint32_t SurfaceFlinger::setClientStateLocked(
2381 const sp<Client>& client,
2382 const layer_state_t& s)
2383{
2384 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002385 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002386 if (layer != 0) {
2387 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002388 bool geometryAppliesWithResize =
2389 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002390 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002391 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002392 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002393 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002394 }
2395 if (what & layer_state_t::eLayerChanged) {
2396 // NOTE: index needs to be calculated before we update the state
2397 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002398 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002399 mCurrentState.layersSortedByZ.removeAt(idx);
2400 mCurrentState.layersSortedByZ.add(layer);
2401 // we need traversal (state changed)
2402 // AND transaction (list changed)
2403 flags |= eTransactionNeeded|eTraversalNeeded;
2404 }
2405 }
2406 if (what & layer_state_t::eSizeChanged) {
2407 if (layer->setSize(s.w, s.h)) {
2408 flags |= eTraversalNeeded;
2409 }
2410 }
2411 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002412 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002413 flags |= eTraversalNeeded;
2414 }
2415 if (what & layer_state_t::eMatrixChanged) {
2416 if (layer->setMatrix(s.matrix))
2417 flags |= eTraversalNeeded;
2418 }
2419 if (what & layer_state_t::eTransparentRegionChanged) {
2420 if (layer->setTransparentRegionHint(s.transparentRegion))
2421 flags |= eTraversalNeeded;
2422 }
Dan Stoza23116082015-06-18 14:58:39 -07002423 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002424 if (layer->setFlags(s.flags, s.mask))
2425 flags |= eTraversalNeeded;
2426 }
2427 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002428 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002429 flags |= eTraversalNeeded;
2430 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002431 if (what & layer_state_t::eFinalCropChanged) {
2432 if (layer->setFinalCrop(s.finalCrop))
2433 flags |= eTraversalNeeded;
2434 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002435 if (what & layer_state_t::eLayerStackChanged) {
2436 // NOTE: index needs to be calculated before we update the state
2437 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002438 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002439 mCurrentState.layersSortedByZ.removeAt(idx);
2440 mCurrentState.layersSortedByZ.add(layer);
2441 // we need traversal (state changed)
2442 // AND transaction (list changed)
2443 flags |= eTransactionNeeded|eTraversalNeeded;
2444 }
2445 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002446 if (what & layer_state_t::eDeferTransaction) {
2447 layer->deferTransactionUntil(s.handle, s.frameNumber);
2448 // We don't trigger a traversal here because if no other state is
2449 // changed, we don't want this to cause any more work
2450 }
Robert Carrc3574f72016-03-24 12:19:32 -07002451 if (what & layer_state_t::eOverrideScalingModeChanged) {
2452 layer->setOverrideScalingMode(s.overrideScalingMode);
2453 // We don't trigger a traversal here because if no other state is
2454 // changed, we don't want this to cause any more work
2455 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002456 }
2457 return flags;
2458}
2459
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002460status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002461 const String8& name,
2462 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002463 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2464 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002466 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002467 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002468 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002469 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002470 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002471 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002472
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002473 status_t result = NO_ERROR;
2474
2475 sp<Layer> layer;
2476
Mathias Agopian3165cc22012-08-08 19:42:09 -07002477 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2478 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002479 result = createNormalLayer(client,
2480 name, w, h, flags, format,
2481 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002483 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002484 result = createDimLayer(client,
2485 name, w, h, flags,
2486 handle, gbp, &layer);
2487 break;
2488 default:
2489 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490 break;
2491 }
2492
Dan Stoza7d89d062015-04-30 13:29:25 -07002493 if (result != NO_ERROR) {
2494 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002495 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002496
2497 result = addClientLayer(client, *handle, *gbp, layer);
2498 if (result != NO_ERROR) {
2499 return result;
2500 }
2501
2502 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002503 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504}
2505
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002506status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2507 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2508 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509{
2510 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002511 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512 case PIXEL_FORMAT_TRANSPARENT:
2513 case PIXEL_FORMAT_TRANSLUCENT:
2514 format = PIXEL_FORMAT_RGBA_8888;
2515 break;
2516 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002517 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 break;
2519 }
2520
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002521 *outLayer = new Layer(this, client, name, w, h, flags);
2522 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2523 if (err == NO_ERROR) {
2524 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002525 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002527
2528 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2529 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530}
2531
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002532status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2533 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2534 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002535{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002536 *outLayer = new LayerDim(this, client, name, w, h, flags);
2537 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002538 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002539 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002540}
2541
Mathias Agopianac9fa422013-02-11 16:40:36 -08002542status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543{
Mathias Agopian67106042013-03-14 19:18:13 -07002544 // called by the window manager when it wants to remove a Layer
2545 status_t err = NO_ERROR;
2546 sp<Layer> l(client->getLayerUser(handle));
2547 if (l != NULL) {
2548 err = removeLayer(l);
2549 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2550 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002551 }
2552 return err;
2553}
2554
Mathias Agopian13127d82013-03-05 17:47:11 -08002555status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002556{
Mathias Agopian67106042013-03-14 19:18:13 -07002557 // called by ~LayerCleaner() when all references to the IBinder (handle)
2558 // are gone
Dan Stoza92cd24e2016-08-09 13:21:03 -07002559 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002560}
2561
Mathias Agopianb60314a2012-04-10 22:09:54 -07002562// ---------------------------------------------------------------------------
2563
Andy McFadden13a082e2012-08-24 10:16:42 -07002564void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002565 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002566 Vector<ComposerState> state;
2567 Vector<DisplayState> displays;
2568 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002569 d.what = DisplayState::eDisplayProjectionChanged |
2570 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002571 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002572 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002573 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002574 d.frame.makeInvalid();
2575 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002576 d.width = 0;
2577 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002578 displays.add(d);
2579 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002580 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002581
Dan Stoza9e56aa02015-11-02 13:00:03 -08002582 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2583 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002584 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002585}
2586
2587void SurfaceFlinger::initializeDisplays() {
2588 class MessageScreenInitialized : public MessageBase {
2589 SurfaceFlinger* flinger;
2590 public:
2591 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2592 virtual bool handler() {
2593 flinger->onInitializeDisplays();
2594 return true;
2595 }
2596 };
2597 sp<MessageBase> msg = new MessageScreenInitialized(this);
2598 postMessageAsync(msg); // we may be called from main thread, use async message
2599}
2600
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002601void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2602 int mode) {
2603 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2604 this);
2605 int32_t type = hw->getDisplayType();
2606 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002607
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002608 if (mode == currentMode) {
2609 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002610 return;
2611 }
2612
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002613 hw->setPowerMode(mode);
2614 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2615 ALOGW("Trying to set power mode for virtual display");
2616 return;
2617 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002618
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002619 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002620 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002621 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002622 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2623 // FIXME: eventthread only knows about the main display right now
2624 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002625 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002626 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002627
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002628 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002629 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002630 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002631
2632 struct sched_param param = {0};
2633 param.sched_priority = 1;
2634 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2635 ALOGW("Couldn't set SCHED_FIFO on display on");
2636 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002637 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002638 // Turn off the display
2639 struct sched_param param = {0};
2640 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2641 ALOGW("Couldn't set SCHED_OTHER on display off");
2642 }
2643
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002644 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002645 disableHardwareVsync(true); // also cancels any in-progress resync
2646
Mathias Agopiancde87a32012-09-13 14:09:01 -07002647 // FIXME: eventthread only knows about the main display right now
2648 mEventThread->onScreenReleased();
2649 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002650
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002651 getHwComposer().setPowerMode(type, mode);
2652 mVisibleRegionsDirty = true;
2653 // from this point on, SF will stop drawing on this display
2654 } else {
2655 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002656 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002657}
2658
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002659void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2660 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002661 SurfaceFlinger& mFlinger;
2662 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002663 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002664 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002665 MessageSetPowerMode(SurfaceFlinger& flinger,
2666 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2667 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002668 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002669 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002670 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002671 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002672 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002673 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002674 ALOGW("Attempt to set power mode = %d for virtual display",
2675 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002676 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002677 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002678 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002679 return true;
2680 }
2681 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002682 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002683 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002684}
2685
2686// ---------------------------------------------------------------------------
2687
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2689{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002691
Mathias Agopianbd115332013-04-18 16:41:04 -07002692 IPCThreadState* ipc = IPCThreadState::self();
2693 const int pid = ipc->getCallingPid();
2694 const int uid = ipc->getCallingUid();
2695 if ((uid != AID_SHELL) &&
2696 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002697 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002698 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002700 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002701 // (this would indicate SF is stuck, but we want to be able to
2702 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002703 status_t err = mStateLock.timedLock(s2ns(1));
2704 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002705 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002706 result.appendFormat(
2707 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2708 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002709 }
2710
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002711 bool dumpAll = true;
2712 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002713 size_t numArgs = args.size();
2714 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002715 if ((index < numArgs) &&
2716 (args[index] == String16("--list"))) {
2717 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002718 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002719 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002720 }
2721
2722 if ((index < numArgs) &&
2723 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002724 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002725 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002726 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002727 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002728
2729 if ((index < numArgs) &&
2730 (args[index] == String16("--latency-clear"))) {
2731 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002732 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002733 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002734 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002735
2736 if ((index < numArgs) &&
2737 (args[index] == String16("--dispsync"))) {
2738 index++;
2739 mPrimaryDispSync.dump(result);
2740 dumpAll = false;
2741 }
Dan Stozab90cf072015-03-05 11:05:59 -08002742
2743 if ((index < numArgs) &&
2744 (args[index] == String16("--static-screen"))) {
2745 index++;
2746 dumpStaticScreenStats(result);
2747 dumpAll = false;
2748 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002749
2750 if ((index < numArgs) &&
2751 (args[index] == String16("--fences"))) {
2752 index++;
2753 mFenceTracker.dump(&result);
2754 dumpAll = false;
2755 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002756 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002757
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002758 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002759 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002760 }
2761
Mathias Agopian9795c422009-08-26 16:36:26 -07002762 if (locked) {
2763 mStateLock.unlock();
2764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 }
2766 write(fd, result.string(), result.size());
2767 return NO_ERROR;
2768}
2769
Dan Stozac7014012014-02-14 15:03:43 -08002770void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2771 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002772{
2773 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2774 const size_t count = currentLayers.size();
2775 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002776 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002777 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002778 }
2779}
2780
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002781void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002782 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002783{
2784 String8 name;
2785 if (index < args.size()) {
2786 name = String8(args[index]);
2787 index++;
2788 }
2789
Dan Stoza9e56aa02015-11-02 13:00:03 -08002790 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2791 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002792 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002793
2794 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002795 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002796 } else {
2797 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2798 const size_t count = currentLayers.size();
2799 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002800 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002801 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002802 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002803 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002804 }
2805 }
2806}
2807
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002808void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002809 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002810{
2811 String8 name;
2812 if (index < args.size()) {
2813 name = String8(args[index]);
2814 index++;
2815 }
2816
2817 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2818 const size_t count = currentLayers.size();
2819 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002820 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002821 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002822 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002823 }
2824 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002825
Svetoslavd85084b2014-03-20 10:28:31 -07002826 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002827}
2828
Jamie Gennis6547ff42013-07-16 20:12:42 -07002829// This should only be called from the main thread. Otherwise it would need
2830// the lock and should use mCurrentState rather than mDrawingState.
2831void SurfaceFlinger::logFrameStats() {
2832 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2833 const size_t count = drawingLayers.size();
2834 for (size_t i=0 ; i<count ; i++) {
2835 const sp<Layer>& layer(drawingLayers[i]);
2836 layer->logFrameStats();
2837 }
2838
2839 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2840}
2841
Andy McFadden4803b742012-09-24 19:07:20 -07002842/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2843{
2844 static const char* config =
2845 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002846#ifdef HAS_CONTEXT_PRIORITY
2847 " HAS_CONTEXT_PRIORITY"
2848#endif
2849#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2850 " NEVER_DEFAULT_TO_ASYNC_MODE"
2851#endif
2852#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2853 " TARGET_DISABLE_TRIPLE_BUFFERING"
2854#endif
2855 "]";
2856 result.append(config);
2857}
2858
Dan Stozab90cf072015-03-05 11:05:59 -08002859void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2860{
2861 result.appendFormat("Static screen stats:\n");
2862 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2863 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2864 float percent = 100.0f *
2865 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2866 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2867 b + 1, bucketTimeSec, percent);
2868 }
2869 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2870 float percent = 100.0f *
2871 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2872 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2873 NUM_BUCKETS - 1, bucketTimeSec, percent);
2874}
2875
Dan Stozae77c7662016-05-13 11:37:28 -07002876void SurfaceFlinger::recordBufferingStats(const char* layerName,
2877 std::vector<OccupancyTracker::Segment>&& history) {
2878 Mutex::Autolock lock(mBufferingStatsMutex);
2879 auto& stats = mBufferingStats[layerName];
2880 for (const auto& segment : history) {
2881 if (!segment.usedThirdBuffer) {
2882 stats.twoBufferTime += segment.totalTime;
2883 }
2884 if (segment.occupancyAverage < 1.0f) {
2885 stats.doubleBufferedTime += segment.totalTime;
2886 } else if (segment.occupancyAverage < 2.0f) {
2887 stats.tripleBufferedTime += segment.totalTime;
2888 }
2889 ++stats.numSegments;
2890 stats.totalTime += segment.totalTime;
2891 }
2892}
2893
2894void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2895 result.append("Buffering stats:\n");
2896 result.append(" [Layer name] <Active time> <Two buffer> "
2897 "<Double buffered> <Triple buffered>\n");
2898 Mutex::Autolock lock(mBufferingStatsMutex);
2899 typedef std::tuple<std::string, float, float, float> BufferTuple;
2900 std::map<float, BufferTuple, std::greater<float>> sorted;
2901 for (const auto& statsPair : mBufferingStats) {
2902 const char* name = statsPair.first.c_str();
2903 const BufferingStats& stats = statsPair.second;
2904 if (stats.numSegments == 0) {
2905 continue;
2906 }
2907 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2908 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2909 stats.totalTime;
2910 float doubleBufferRatio = static_cast<float>(
2911 stats.doubleBufferedTime) / stats.totalTime;
2912 float tripleBufferRatio = static_cast<float>(
2913 stats.tripleBufferedTime) / stats.totalTime;
2914 sorted.insert({activeTime, {name, twoBufferRatio,
2915 doubleBufferRatio, tripleBufferRatio}});
2916 }
2917 for (const auto& sortedPair : sorted) {
2918 float activeTime = sortedPair.first;
2919 const BufferTuple& values = sortedPair.second;
2920 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2921 std::get<0>(values).c_str(), activeTime,
2922 std::get<1>(values), std::get<2>(values),
2923 std::get<3>(values));
2924 }
2925 result.append("\n");
2926}
2927
2928
Mathias Agopian74d211a2013-04-22 16:55:35 +02002929void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2930 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002931{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002932 bool colorize = false;
2933 if (index < args.size()
2934 && (args[index] == String16("--color"))) {
2935 colorize = true;
2936 index++;
2937 }
2938
2939 Colorizer colorizer(colorize);
2940
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002941 // figure out if we're stuck somewhere
2942 const nsecs_t now = systemTime();
2943 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2944 const nsecs_t inTransaction(mDebugInTransaction);
2945 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2946 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2947
2948 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002949 * Dump library configuration.
2950 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002951
2952 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002953 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002954 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002955 appendSfConfigString(result);
2956 appendUiConfigString(result);
2957 appendGuiConfigString(result);
2958 result.append("\n");
2959
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002960 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002961 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002962 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002963 result.append(SyncFeatures::getInstance().toString());
2964 result.append("\n");
2965
Dan Stoza9e56aa02015-11-02 13:00:03 -08002966 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2967
Andy McFadden41d67d72014-04-25 16:58:34 -07002968 colorizer.bold(result);
2969 result.append("DispSync configuration: ");
2970 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002971 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2972 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002973 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2974 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002975 result.append("\n");
2976
Dan Stozab90cf072015-03-05 11:05:59 -08002977 // Dump static screen stats
2978 result.append("\n");
2979 dumpStaticScreenStats(result);
2980 result.append("\n");
2981
Dan Stozae77c7662016-05-13 11:37:28 -07002982 dumpBufferingStats(result);
2983
Andy McFadden4803b742012-09-24 19:07:20 -07002984 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002985 * Dump the visible layer list
2986 */
2987 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2988 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002989 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002990 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002991 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002992 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002993 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002994 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002995 }
2996
2997 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002998 * Dump Display state
2999 */
3000
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003001 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003002 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003003 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003004 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3005 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003006 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003007 }
3008
3009 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003010 * Dump SurfaceFlinger global state
3011 */
3012
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003013 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003014 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003015 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003016
Mathias Agopian888c8222012-08-04 21:10:38 -07003017 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003018 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003019
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003020 colorizer.bold(result);
3021 result.appendFormat("EGL implementation : %s\n",
3022 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3023 colorizer.reset(result);
3024 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003025 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003026
Mathias Agopian875d8e12013-06-07 15:35:48 -07003027 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003028
Mathias Agopian42977342012-08-05 00:40:46 -07003029 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003030 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3031 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003032 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003033 " last eglSwapBuffers() time: %f us\n"
3034 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003035 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003036 " refresh-rate : %f fps\n"
3037 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003038 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003039 " gpu_to_cpu_unsupported : %d\n"
3040 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003041 mLastSwapBufferTime/1000.0,
3042 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003043 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 1e9 / activeConfig->getVsyncPeriod(),
3045 activeConfig->getDpiX(),
3046 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003047 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003048
Mathias Agopian74d211a2013-04-22 16:55:35 +02003049 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003050 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003051
Mathias Agopian74d211a2013-04-22 16:55:35 +02003052 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003053 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003054
3055 /*
3056 * VSYNC state
3057 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003058 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003059 result.append("\n");
3060
3061 /*
3062 * HWC layer minidump
3063 */
3064 for (size_t d = 0; d < mDisplays.size(); d++) {
3065 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3066 int32_t hwcId = displayDevice->getHwcDisplayId();
3067 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3068 continue;
3069 }
3070
3071 result.appendFormat("Display %d HWC layers:\n", hwcId);
3072 Layer::miniDumpHeader(result);
3073 for (size_t l = 0; l < count; l++) {
3074 const sp<Layer>& layer(currentLayers[l]);
3075 layer->miniDump(result, hwcId);
3076 }
3077 result.append("\n");
3078 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003079
3080 /*
3081 * Dump HWComposer state
3082 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003083 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003084 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003085 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003086 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003087 result.appendFormat(" h/w composer %s\n",
3088 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003089 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003090
3091 /*
3092 * Dump gralloc state
3093 */
3094 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3095 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003096}
3097
Mathias Agopian13127d82013-03-05 17:47:11 -08003098const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003099SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003100 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003101 wp<IBinder> dpy;
3102 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3103 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3104 dpy = mDisplays.keyAt(i);
3105 break;
3106 }
3107 }
3108 if (dpy == NULL) {
3109 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3110 // Just use the primary display so we have something to return
3111 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3112 }
3113 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003114}
3115
Keun young Park63f165f2012-08-31 10:53:36 -07003116bool SurfaceFlinger::startDdmConnection()
3117{
3118 void* libddmconnection_dso =
3119 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3120 if (!libddmconnection_dso) {
3121 return false;
3122 }
3123 void (*DdmConnection_start)(const char* name);
3124 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003125 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003126 if (!DdmConnection_start) {
3127 dlclose(libddmconnection_dso);
3128 return false;
3129 }
3130 (*DdmConnection_start)(getServiceName());
3131 return true;
3132}
3133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134status_t SurfaceFlinger::onTransact(
3135 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3136{
3137 switch (code) {
3138 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003139 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003140 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003142 case CLEAR_ANIMATION_FRAME_STATS:
3143 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003144 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003145 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 {
3147 // codes that require permission check
3148 IPCThreadState* ipc = IPCThreadState::self();
3149 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003150 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003151 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003152 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003153 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003154 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3155 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003157 break;
3158 }
3159 case CAPTURE_SCREEN:
3160 {
3161 // codes that require permission check
3162 IPCThreadState* ipc = IPCThreadState::self();
3163 const int pid = ipc->getCallingPid();
3164 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003165 if ((uid != AID_GRAPHICS) &&
3166 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003167 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003168 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3169 return PERMISSION_DENIED;
3170 }
3171 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 }
3173 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003174
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3176 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003177 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003178 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003179 IPCThreadState* ipc = IPCThreadState::self();
3180 const int pid = ipc->getCallingPid();
3181 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003182 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003183 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 return PERMISSION_DENIED;
3185 }
3186 int n;
3187 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003188 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003189 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 return NO_ERROR;
3191 case 1002: // SHOW_UPDATES
3192 n = data.readInt32();
3193 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003194 invalidateHwcGeometry();
3195 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003198 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003199 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003200 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003201 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003202 setTransactionFlags(
3203 eTransactionNeeded|
3204 eDisplayTransactionNeeded|
3205 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003206 return NO_ERROR;
3207 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003208 case 1006:{ // send empty update
3209 signalRefresh();
3210 return NO_ERROR;
3211 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003212 case 1008: // toggle use of hw composer
3213 n = data.readInt32();
3214 mDebugDisableHWC = n ? 1 : 0;
3215 invalidateHwcGeometry();
3216 repaintEverything();
3217 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003218 case 1009: // toggle use of transform hint
3219 n = data.readInt32();
3220 mDebugDisableTransformHint = n ? 1 : 0;
3221 invalidateHwcGeometry();
3222 repaintEverything();
3223 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003225 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003226 reply->writeInt32(0);
3227 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003228 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003229 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 return NO_ERROR;
3231 case 1013: {
3232 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003233 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3234 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003235 return NO_ERROR;
3236 }
3237 case 1014: {
3238 // daltonize
3239 n = data.readInt32();
3240 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003241 case 1:
3242 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3243 break;
3244 case 2:
3245 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3246 break;
3247 case 3:
3248 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3249 break;
3250 default:
3251 mDaltonizer.setType(ColorBlindnessType::None);
3252 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003253 }
3254 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003255 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003256 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003257 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003258 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003259 invalidateHwcGeometry();
3260 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003261 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003263 case 1015: {
3264 // apply a color matrix
3265 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003266 if (n) {
3267 // color matrix is sent as mat3 matrix followed by vec3
3268 // offset, then packed into a mat4 where the last row is
3269 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003270 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003271 for (size_t j = 0; j < 4; j++) {
3272 mColorMatrix[i][j] = data.readFloat();
3273 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003274 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003275 } else {
3276 mColorMatrix = mat4();
3277 }
3278 invalidateHwcGeometry();
3279 repaintEverything();
3280 return NO_ERROR;
3281 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003282 // This is an experimental interface
3283 // Needs to be shifted to proper binder interface when we productize
3284 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003285 n = data.readInt32();
3286 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003287 return NO_ERROR;
3288 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003289 case 1017: {
3290 n = data.readInt32();
3291 mForceFullDamage = static_cast<bool>(n);
3292 return NO_ERROR;
3293 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003294 case 1018: { // Modify Choreographer's phase offset
3295 n = data.readInt32();
3296 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3297 return NO_ERROR;
3298 }
3299 case 1019: { // Modify SurfaceFlinger's phase offset
3300 n = data.readInt32();
3301 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3302 return NO_ERROR;
3303 }
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07003304 case 1021: { // Disable HWC virtual displays
3305 n = data.readInt32();
3306 mUseHwcVirtualDisplays = !n;
3307 return NO_ERROR;
3308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309 }
3310 }
3311 return err;
3312}
3313
Mathias Agopian53331da2011-08-22 21:44:41 -07003314void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003315 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003316 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003317}
3318
Mathias Agopian59119e62010-10-11 12:37:43 -07003319// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003320// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003321// ---------------------------------------------------------------------------
3322
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003323/* The code below is here to handle b/8734824
3324 *
3325 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003326 * from the surfaceflinger thread to the calling binder thread, where they
3327 * are executed. This allows the calling thread in the calling process to be
3328 * reused and not depend on having "enough" binder threads to handle the
3329 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003330 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003331class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003332 /* Parts of GraphicProducerWrapper are run on two different threads,
3333 * communicating by sending messages via Looper but also by shared member
3334 * data. Coherence maintenance is subtle and in places implicit (ugh).
3335 *
3336 * Don't rely on Looper's sendMessage/handleMessage providing
3337 * release/acquire semantics for any data not actually in the Message.
3338 * Data going from surfaceflinger to binder threads needs to be
3339 * synchronized explicitly.
3340 *
3341 * Barrier open/wait do provide release/acquire semantics. This provides
3342 * implicit synchronization for data coming back from binder to
3343 * surfaceflinger threads.
3344 */
3345
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003346 sp<IGraphicBufferProducer> impl;
3347 sp<Looper> looper;
3348 status_t result;
3349 bool exitPending;
3350 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003351 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003352 uint32_t code;
3353 Parcel const* data;
3354 Parcel* reply;
3355
3356 enum {
3357 MSG_API_CALL,
3358 MSG_EXIT
3359 };
3360
3361 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003362 * Called on surfaceflinger thread. This is called by our "fake"
3363 * BpGraphicBufferProducer. We package the data and reply Parcel and
3364 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003365 */
3366 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003367 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003368 this->code = code;
3369 this->data = &data;
3370 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003371 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003372 // if we've exited, we run the message synchronously right here.
3373 // note (JH): as far as I can tell from looking at the code, this
3374 // never actually happens. if it does, i'm not sure if it happens
3375 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003376 handleMessage(Message(MSG_API_CALL));
3377 } else {
3378 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003379 // Prevent stores to this->{code, data, reply} from being
3380 // reordered later than the construction of Message.
3381 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003382 looper->sendMessage(this, Message(MSG_API_CALL));
3383 barrier.wait();
3384 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003385 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003386 }
3387
3388 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003389 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003390 * call the real BpGraphicBufferProducer.
3391 */
3392 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003393 int what = message.what;
3394 // Prevent reads below from happening before the read from Message
3395 atomic_thread_fence(memory_order_acquire);
3396 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003397 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003398 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003399 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003400 exitRequested = true;
3401 }
3402 }
3403
3404public:
Jesse Hallb154c422014-07-13 12:47:02 -07003405 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3406 : impl(impl),
3407 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003408 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003409 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003410 exitRequested(false),
3411 code(0),
3412 data(NULL),
3413 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003414 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003415
Jesse Hallb154c422014-07-13 12:47:02 -07003416 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003417 status_t waitForResponse() {
3418 do {
3419 looper->pollOnce(-1);
3420 } while (!exitRequested);
3421 return result;
3422 }
3423
Jesse Hallb154c422014-07-13 12:47:02 -07003424 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003425 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003426 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003427 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003428 // Ensure this->result is visible to the binder thread before it
3429 // handles the message.
3430 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003431 looper->sendMessage(this, Message(MSG_EXIT));
3432 }
3433};
3434
3435
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003436status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3437 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003438 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003439 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003440 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003441
3442 if (CC_UNLIKELY(display == 0))
3443 return BAD_VALUE;
3444
3445 if (CC_UNLIKELY(producer == 0))
3446 return BAD_VALUE;
3447
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003448 // if we have secure windows on this display, never allow the screen capture
3449 // unless the producer interface is local (i.e.: we can take a screenshot for
3450 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003451 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003452
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003453 // Convert to surfaceflinger's internal rotation type.
3454 Transform::orientation_flags rotationFlags;
3455 switch (rotation) {
3456 case ISurfaceComposer::eRotateNone:
3457 rotationFlags = Transform::ROT_0;
3458 break;
3459 case ISurfaceComposer::eRotate90:
3460 rotationFlags = Transform::ROT_90;
3461 break;
3462 case ISurfaceComposer::eRotate180:
3463 rotationFlags = Transform::ROT_180;
3464 break;
3465 case ISurfaceComposer::eRotate270:
3466 rotationFlags = Transform::ROT_270;
3467 break;
3468 default:
3469 rotationFlags = Transform::ROT_0;
3470 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3471 break;
3472 }
3473
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003474 class MessageCaptureScreen : public MessageBase {
3475 SurfaceFlinger* flinger;
3476 sp<IBinder> display;
3477 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003478 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003479 uint32_t reqWidth, reqHeight;
3480 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003481 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003482 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003483 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003484 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003485 public:
3486 MessageCaptureScreen(SurfaceFlinger* flinger,
3487 const sp<IBinder>& display,
3488 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003489 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003490 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003491 bool useIdentityTransform,
3492 Transform::orientation_flags rotation,
3493 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003494 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003495 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003496 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003497 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003498 rotation(rotation), result(PERMISSION_DENIED),
3499 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003500 {
3501 }
3502 status_t getResult() const {
3503 return result;
3504 }
3505 virtual bool handler() {
3506 Mutex::Autolock _l(flinger->mStateLock);
3507 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003508 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003509 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003510 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003511 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003512 return true;
3513 }
3514 };
3515
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003516 // this creates a "fake" BBinder which will serve as a "fake" remote
3517 // binder to receive the marshaled calls and forward them to the
3518 // real remote (a BpGraphicBufferProducer)
3519 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3520
3521 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3522 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003523 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003524 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003525 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003526 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003527
3528 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003529 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003530 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003531 }
3532 return res;
3533}
3534
Mathias Agopian180f10d2013-04-10 22:55:41 -07003535
3536void SurfaceFlinger::renderScreenImplLocked(
3537 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003538 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003539 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003540 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003541{
3542 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003543 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003544
3545 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003546 const int32_t hw_w = hw->getWidth();
3547 const int32_t hw_h = hw->getHeight();
3548 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003549 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003550
Dan Stozac1879002014-05-22 15:59:05 -07003551 // if a default or invalid sourceCrop is passed in, set reasonable values
3552 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3553 !sourceCrop.isValid()) {
3554 sourceCrop.setLeftTop(Point(0, 0));
3555 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3556 }
3557
3558 // ensure that sourceCrop is inside screen
3559 if (sourceCrop.left < 0) {
3560 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3561 }
Dan Stozabe31f442014-06-11 11:20:54 -07003562 if (sourceCrop.right > hw_w) {
3563 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003564 }
3565 if (sourceCrop.top < 0) {
3566 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3567 }
Dan Stozabe31f442014-06-11 11:20:54 -07003568 if (sourceCrop.bottom > hw_h) {
3569 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003570 }
3571
Mathias Agopian180f10d2013-04-10 22:55:41 -07003572 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003573 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003574
3575 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003576 engine.setViewportAndProjection(
3577 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003578 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003579
3580 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003581 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003582
3583 const LayerVector& layers( mDrawingState.layersSortedByZ );
3584 const size_t count = layers.size();
3585 for (size_t i=0 ; i<count ; ++i) {
3586 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003587 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003588 if (state.layerStack == hw->getLayerStack()) {
3589 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3590 if (layer->isVisible()) {
3591 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003592 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003593 if (filtering) layer->setFiltering(false);
3594 }
3595 }
3596 }
3597 }
3598
Mathias Agopian931bda12013-08-28 18:11:46 -07003599 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003600}
3601
3602
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003603status_t SurfaceFlinger::captureScreenImplLocked(
3604 const sp<const DisplayDevice>& hw,
3605 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003606 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003607 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003608 bool useIdentityTransform, Transform::orientation_flags rotation,
3609 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003610{
3611 ATRACE_CALL();
3612
Mathias Agopian180f10d2013-04-10 22:55:41 -07003613 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003614 uint32_t hw_w = hw->getWidth();
3615 uint32_t hw_h = hw->getHeight();
3616
3617 if (rotation & Transform::ROT_90) {
3618 std::swap(hw_w, hw_h);
3619 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003620
Mathias Agopian180f10d2013-04-10 22:55:41 -07003621 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3622 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3623 reqWidth, reqHeight, hw_w, hw_h);
3624 return BAD_VALUE;
3625 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003626
Mathias Agopian180f10d2013-04-10 22:55:41 -07003627 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3628 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3629
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003630 bool secureLayerIsVisible = false;
3631 const LayerVector& layers(mDrawingState.layersSortedByZ);
3632 const size_t count = layers.size();
3633 for (size_t i = 0 ; i < count ; ++i) {
3634 const sp<Layer>& layer(layers[i]);
3635 const Layer::State& state(layer->getDrawingState());
3636 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3637 state.z <= maxLayerZ && layer->isVisible() &&
3638 layer->isSecure()) {
3639 secureLayerIsVisible = true;
3640 }
3641 }
3642
3643 if (!isLocalScreenshot && secureLayerIsVisible) {
3644 ALOGW("FB is protected: PERMISSION_DENIED");
3645 return PERMISSION_DENIED;
3646 }
3647
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003648 // create a surface (because we're a producer, and we need to
3649 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003650 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003651
3652 // Put the screenshot Surface into async mode so that
3653 // Layer::headFenceHasSignaled will always return true and we'll latch the
3654 // first buffer regardless of whether or not its acquire fence has
3655 // signaled. This is needed to avoid a race condition in the rotation
3656 // animation. See b/30209608
3657 sur->setAsyncMode(true);
3658
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003659 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003660
Michael Lentine5a16a622015-05-21 13:48:24 -07003661 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3662 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003663 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3664 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003665
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003666 int err = 0;
3667 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003668 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003669 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3670 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003671
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003672 if (err == NO_ERROR) {
3673 ANativeWindowBuffer* buffer;
3674 /* TODO: Once we have the sync framework everywhere this can use
3675 * server-side waits on the fence that dequeueBuffer returns.
3676 */
3677 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3678 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003679 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003680 // create an EGLImage from the buffer so we can later
3681 // turn it into a texture
3682 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3683 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3684 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003685 // this binds the given EGLImage as a framebuffer for the
3686 // duration of this scope.
3687 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3688 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003689 // this will in fact render into our dequeued buffer
3690 // via an FBO, which means we didn't have to create
3691 // an EGLSurface and therefore we're not
3692 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003693 renderScreenImplLocked(
3694 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3695 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003696
Riley Andrews86639902014-08-15 12:27:24 -07003697 // Attempt to create a sync khr object that can produce a sync point. If that
3698 // isn't available, create a non-dupable sync object in the fallback path and
3699 // wait on it directly.
3700 EGLSyncKHR sync;
3701 if (!DEBUG_SCREENSHOTS) {
3702 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003703 // native fence fd will not be populated until flush() is done.
3704 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003705 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003706 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003707 }
Riley Andrews86639902014-08-15 12:27:24 -07003708 if (sync != EGL_NO_SYNC_KHR) {
3709 // get the sync fd
3710 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3711 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3712 ALOGW("captureScreen: failed to dup sync khr object");
3713 syncFd = -1;
3714 }
3715 eglDestroySyncKHR(mEGLDisplay, sync);
3716 } else {
3717 // fallback path
3718 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3719 if (sync != EGL_NO_SYNC_KHR) {
3720 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3721 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3722 EGLint eglErr = eglGetError();
3723 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3724 ALOGW("captureScreen: fence wait timed out");
3725 } else {
3726 ALOGW_IF(eglErr != EGL_SUCCESS,
3727 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3728 }
3729 eglDestroySyncKHR(mEGLDisplay, sync);
3730 } else {
3731 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3732 }
3733 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003734 if (DEBUG_SCREENSHOTS) {
3735 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3736 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3737 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3738 hw, minLayerZ, maxLayerZ);
3739 delete [] pixels;
3740 }
3741
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003742 } else {
3743 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3744 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003745 window->cancelBuffer(window, buffer, syncFd);
3746 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003747 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003748 // destroy our image
3749 eglDestroyImageKHR(mEGLDisplay, image);
3750 } else {
3751 result = BAD_VALUE;
3752 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003753 if (buffer) {
3754 // queueBuffer takes ownership of syncFd
3755 result = window->queueBuffer(window, buffer, syncFd);
3756 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003757 }
3758 } else {
3759 result = BAD_VALUE;
3760 }
3761 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3762 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003763
Mathias Agopian74c40c02010-09-29 13:02:36 -07003764 return result;
3765}
3766
Mathias Agopiand5556842013-09-19 17:08:37 -07003767void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3768 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003769 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003770 for (size_t y=0 ; y<h ; y++) {
3771 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3772 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003773 if (p[x] != 0xFF000000) return;
3774 }
3775 }
3776 ALOGE("*** we just took a black screenshot ***\n"
3777 "requested minz=%d, maxz=%d, layerStack=%d",
3778 minLayerZ, maxLayerZ, hw->getLayerStack());
3779 const LayerVector& layers( mDrawingState.layersSortedByZ );
3780 const size_t count = layers.size();
3781 for (size_t i=0 ; i<count ; ++i) {
3782 const sp<Layer>& layer(layers[i]);
3783 const Layer::State& state(layer->getDrawingState());
3784 const bool visible = (state.layerStack == hw->getLayerStack())
3785 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3786 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003787 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003788 visible ? '+' : '-',
3789 i, layer->getName().string(), state.layerStack, state.z,
3790 layer->isVisible(), state.flags, state.alpha);
3791 }
3792 }
3793}
3794
Pablo Ceballosce796e72016-02-04 19:10:51 -08003795bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3796 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3797 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3798}
3799
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003800// ---------------------------------------------------------------------------
3801
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003802SurfaceFlinger::LayerVector::LayerVector() {
3803}
3804
3805SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003806 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003807}
3808
3809int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3810 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003811{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003812 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003813 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3814 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003815
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003816 uint32_t ls = l->getCurrentState().layerStack;
3817 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003818 if (ls != rs)
3819 return ls - rs;
3820
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003821 uint32_t lz = l->getCurrentState().z;
3822 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003823 if (lz != rz)
3824 return lz - rz;
3825
3826 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003827}
3828
3829// ---------------------------------------------------------------------------
3830
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003831SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003832 : type(DisplayDevice::DISPLAY_ID_INVALID),
3833 layerStack(DisplayDevice::NO_LAYER_STACK),
3834 orientation(0),
3835 width(0),
3836 height(0),
3837 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003838}
3839
Pablo Ceballos53390e12015-08-04 11:25:59 -07003840SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3841 DisplayDevice::DisplayType type, bool isSecure)
3842 : type(type),
3843 layerStack(DisplayDevice::NO_LAYER_STACK),
3844 orientation(0),
3845 width(0),
3846 height(0),
3847 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003848 viewport.makeInvalid();
3849 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003850}
3851
3852// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003855
3856
3857#if defined(__gl_h_)
3858#error "don't include gl/gl.h in this file"
3859#endif
3860
3861#if defined(__gl2_h_)
3862#error "don't include gl2/gl2.h in this file"
3863#endif