blob: 5eea3d975054366d04f6c7cadd94dedfcc0dfdcb [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070031#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
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) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800659 if (display == NULL) {
660 ALOGE("%s : display is NULL", __func__);
661 return BAD_VALUE;
662 }
Dan Stoza24a42e92015-03-09 10:04:11 -0700663 sp<DisplayDevice> device(getDisplayDevice(display));
664 if (device != NULL) {
665 return device->getActiveConfig();
666 }
667 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700668}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700669
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700670void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
671 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
672 this);
673 int32_t type = hw->getDisplayType();
674 int currentMode = hw->getActiveConfig();
675
676 if (mode == currentMode) {
677 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
678 return;
679 }
680
681 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
682 ALOGW("Trying to set config for virtual display");
683 return;
684 }
685
686 hw->setActiveConfig(mode);
687 getHwComposer().setActiveConfig(type, mode);
688}
689
690status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
691 class MessageSetActiveConfig: public MessageBase {
692 SurfaceFlinger& mFlinger;
693 sp<IBinder> mDisplay;
694 int mMode;
695 public:
696 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
697 int mode) :
698 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
699 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700700 Vector<DisplayInfo> configs;
701 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700702 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700703 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700704 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700705 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700706 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700707 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
708 if (hw == NULL) {
709 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700710 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700711 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
712 ALOGW("Attempt to set active config = %d for virtual display",
713 mMode);
714 } else {
715 mFlinger.setActiveConfigInternal(hw, mMode);
716 }
717 return true;
718 }
719 };
720 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
721 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700722 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700723}
Michael Wright28f24d02016-07-12 13:30:53 -0700724status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
725 Vector<android_color_mode_t>* outColorModes) {
726 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
727 return BAD_VALUE;
728 }
729
730 if (!display.get()) {
731 return NAME_NOT_FOUND;
732 }
733
734 int32_t type = NAME_NOT_FOUND;
735 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
736 if (display == mBuiltinDisplays[i]) {
737 type = i;
738 break;
739 }
740 }
741
742 if (type < 0) {
743 return type;
744 }
745
746 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
747 outColorModes->clear();
748 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
749
750 return NO_ERROR;
751}
752
753android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
754 sp<DisplayDevice> device(getDisplayDevice(display));
755 if (device != nullptr) {
756 return device->getActiveColorMode();
757 }
758 return static_cast<android_color_mode_t>(BAD_VALUE);
759}
760
761void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
762 android_color_mode_t mode) {
763 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
764 this);
765 int32_t type = hw->getDisplayType();
766 android_color_mode_t currentMode = hw->getActiveColorMode();
767
768 if (mode == currentMode) {
769 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
770 return;
771 }
772
773 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
774 ALOGW("Trying to set config for virtual display");
775 return;
776 }
777
778 hw->setActiveColorMode(mode);
779 getHwComposer().setActiveColorMode(type, mode);
780}
781
782
783status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
784 android_color_mode_t colorMode) {
785 class MessageSetActiveColorMode: public MessageBase {
786 SurfaceFlinger& mFlinger;
787 sp<IBinder> mDisplay;
788 android_color_mode_t mMode;
789 public:
790 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
791 android_color_mode_t mode) :
792 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
793 virtual bool handler() {
794 Vector<android_color_mode_t> modes;
795 mFlinger.getDisplayColorModes(mDisplay, &modes);
796 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
797 if (mMode < 0 || !exists) {
798 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
799 mDisplay.get());
800 return true;
801 }
802 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
803 if (hw == nullptr) {
804 ALOGE("Attempt to set active color mode = %d for null display %p",
805 mMode, mDisplay.get());
806 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
807 ALOGW("Attempt to set active color mode= %d for virtual display",
808 mMode);
809 } else {
810 mFlinger.setActiveColorModeInternal(hw, mMode);
811 }
812 return true;
813 }
814 };
815 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
816 postMessageSync(msg);
817 return NO_ERROR;
818}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700819
Svetoslavd85084b2014-03-20 10:28:31 -0700820status_t SurfaceFlinger::clearAnimationFrameStats() {
821 Mutex::Autolock _l(mStateLock);
822 mAnimFrameTracker.clearStats();
823 return NO_ERROR;
824}
825
826status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
827 Mutex::Autolock _l(mStateLock);
828 mAnimFrameTracker.getStats(outStats);
829 return NO_ERROR;
830}
831
Dan Stozac4f471e2016-03-24 09:31:08 -0700832status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
833 HdrCapabilities* outCapabilities) const {
834 Mutex::Autolock _l(mStateLock);
835
836 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
837 if (displayDevice == nullptr) {
838 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
839 return BAD_VALUE;
840 }
841
842 std::unique_ptr<HdrCapabilities> capabilities =
843 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
844 if (capabilities) {
845 std::swap(*outCapabilities, *capabilities);
846 } else {
847 return BAD_VALUE;
848 }
849
850 return NO_ERROR;
851}
852
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800853// ----------------------------------------------------------------------------
854
855sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800856 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700857}
858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800859// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800860
861void SurfaceFlinger::waitForEvent() {
862 mEventQueue.waitMessage();
863}
864
865void SurfaceFlinger::signalTransaction() {
866 mEventQueue.invalidate();
867}
868
869void SurfaceFlinger::signalLayerUpdate() {
870 mEventQueue.invalidate();
871}
872
873void SurfaceFlinger::signalRefresh() {
874 mEventQueue.refresh();
875}
876
877status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800878 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800879 return mEventQueue.postMessage(msg, reltime);
880}
881
882status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800883 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800884 status_t res = mEventQueue.postMessage(msg, reltime);
885 if (res == NO_ERROR) {
886 msg->wait();
887 }
888 return res;
889}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800890
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700891void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700892 do {
893 waitForEvent();
894 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800895}
896
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700897void SurfaceFlinger::enableHardwareVsync() {
898 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700899 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700900 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700901 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
902 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700903 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700904 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700905}
906
Jesse Hall948fe0c2013-10-14 12:56:09 -0700907void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700908 Mutex::Autolock _l(mHWVsyncLock);
909
Jesse Hall948fe0c2013-10-14 12:56:09 -0700910 if (makeAvailable) {
911 mHWVsyncAvailable = true;
912 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700913 // Hardware vsync is not currently available, so abort the resync
914 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700915 return;
916 }
917
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
919 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700920
921 mPrimaryDispSync.reset();
922 mPrimaryDispSync.setPeriod(period);
923
924 if (!mPrimaryHWVsyncEnabled) {
925 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700926 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
927 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700928 mPrimaryHWVsyncEnabled = true;
929 }
930}
931
Jesse Hall948fe0c2013-10-14 12:56:09 -0700932void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700933 Mutex::Autolock _l(mHWVsyncLock);
934 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700935 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
936 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700937 mPrimaryDispSync.endResync();
938 mPrimaryHWVsyncEnabled = false;
939 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700940 if (makeUnavailable) {
941 mHWVsyncAvailable = false;
942 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700943}
944
Tim Murray4a4e4a22016-04-19 16:29:23 +0000945void SurfaceFlinger::resyncWithRateLimit() {
946 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
947 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700948 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000949 }
950}
951
Dan Stoza9e56aa02015-11-02 13:00:03 -0800952void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700953 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700954
Jamie Gennisd1700752013-10-14 12:22:52 -0700955 { // Scope for the lock
956 Mutex::Autolock _l(mHWVsyncLock);
957 if (type == 0 && mPrimaryHWVsyncEnabled) {
958 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700959 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700960 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700961
962 if (needsHwVsync) {
963 enableHardwareVsync();
964 } else {
965 disableHardwareVsync(false);
966 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700967}
968
Dan Stoza9e56aa02015-11-02 13:00:03 -0800969void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
970 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
971 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
972 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700973
Dan Stoza9e56aa02015-11-02 13:00:03 -0800974 // All non-virtual displays are currently considered secure.
975 bool isSecure = true;
976
977 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
978 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
979 wp<IBinder> token = mBuiltinDisplays[type];
980
981 sp<IGraphicBufferProducer> producer;
982 sp<IGraphicBufferConsumer> consumer;
983 BufferQueue::createBufferQueue(&producer, &consumer,
984 new GraphicBufferAlloc());
985
986 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
987 DisplayDevice::DISPLAY_PRIMARY, consumer);
988 sp<DisplayDevice> hw = new DisplayDevice(this,
989 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
990 producer, mRenderEngine->getEGLConfig());
991 mDisplays.add(token, hw);
992 } else {
993 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700994 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800995 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800996 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700997 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800998 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
999 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001000 }
1001 setTransactionFlags(eDisplayTransactionNeeded);
1002
Andy McFadden9e9689c2012-10-10 18:17:51 -07001003 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001004 }
Mathias Agopian86303202012-07-24 22:46:10 -07001005}
1006
Dan Stoza9e56aa02015-11-02 13:00:03 -08001007void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001008 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001009 getHwComposer().setVsyncEnabled(disp,
1010 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001011}
1012
Mathias Agopian4fec8732012-06-29 14:12:52 -07001013void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001014 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001015 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001016 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001017 bool frameMissed = !mHadClientComposition &&
1018 mPreviousPresentFence != Fence::NO_FENCE &&
1019 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1020 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001021 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001022 signalLayerUpdate();
1023 break;
1024 }
1025
Dan Stoza6b9454d2014-11-07 16:00:59 -08001026 bool refreshNeeded = handleMessageTransaction();
1027 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001028 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001029 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001030 // Signal a refresh if a transaction modified the window state,
1031 // a new buffer was latched, or if HWC has requested a full
1032 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001033 signalRefresh();
1034 }
1035 break;
1036 }
1037 case MessageQueue::REFRESH: {
1038 handleMessageRefresh();
1039 break;
1040 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001041 }
1042}
1043
Dan Stoza6b9454d2014-11-07 16:00:59 -08001044bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001045 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001046 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001047 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001048 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001049 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001050 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001051}
1052
Dan Stoza6b9454d2014-11-07 16:00:59 -08001053bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001054 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001055 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001056}
1057
1058void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001059 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001060
Pablo Ceballos40845df2016-01-25 17:41:15 -08001061 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001062
Dan Stoza05dacfb2016-07-01 13:33:38 -07001063 preComposition();
1064 rebuildLayerStacks();
1065 setUpHWComposer();
1066 doDebugFlashRegions();
1067 doComposition();
1068 postComposition(refreshStartTime);
1069
1070 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001071
1072 mHadClientComposition = false;
1073 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1074 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1075 mHadClientComposition = mHadClientComposition ||
1076 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1077 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001078
Dan Stoza9e56aa02015-11-02 13:00:03 -08001079 // Release any buffers which were replaced this frame
1080 for (auto& layer : mLayersWithQueuedFrames) {
1081 layer->releasePendingBuffer();
1082 }
1083 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001084}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001085
Mathias Agopiancd60f992012-08-16 16:28:27 -07001086void SurfaceFlinger::doDebugFlashRegions()
1087{
1088 // is debugging enabled
1089 if (CC_LIKELY(!mDebugRegion))
1090 return;
1091
1092 const bool repaintEverything = mRepaintEverything;
1093 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1094 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001095 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001096 // transform the dirty region into this screen's coordinate space
1097 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1098 if (!dirtyRegion.isEmpty()) {
1099 // redraw the whole screen
1100 doComposeSurfaces(hw, Region(hw->bounds()));
1101
1102 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001103 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001104 RenderEngine& engine(getRenderEngine());
1105 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1106
Mathias Agopianda27af92012-09-13 18:17:13 -07001107 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001108 }
1109 }
1110 }
1111
1112 postFramebuffer();
1113
1114 if (mDebugRegion > 1) {
1115 usleep(mDebugRegion * 1000);
1116 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001117
Dan Stoza9e56aa02015-11-02 13:00:03 -08001118 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001119 auto& displayDevice = mDisplays[displayId];
1120 if (!displayDevice->isDisplayOn()) {
1121 continue;
1122 }
1123
1124 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001125 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1126 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001127 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001128}
1129
1130void SurfaceFlinger::preComposition()
1131{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 ATRACE_CALL();
1133 ALOGV("preComposition");
1134
Mathias Agopiancd60f992012-08-16 16:28:27 -07001135 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001136 const LayerVector& layers(mDrawingState.layersSortedByZ);
1137 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001138 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001139 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001140 needExtraInvalidate = true;
1141 }
1142 }
1143 if (needExtraInvalidate) {
1144 signalLayerUpdate();
1145 }
1146}
1147
Pablo Ceballos40845df2016-01-25 17:41:15 -08001148void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001149{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 ATRACE_CALL();
1151 ALOGV("postComposition");
1152
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001153 const LayerVector& layers(mDrawingState.layersSortedByZ);
1154 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001155 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001156 bool frameLatched = layers[i]->onPostComposition();
1157 if (frameLatched) {
1158 recordBufferingStats(layers[i]->getName().string(),
1159 layers[i]->getOccupancyHistory(false));
1160 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001161 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001162
Dan Stoza9e56aa02015-11-02 13:00:03 -08001163 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164
1165 if (presentFence->isValid()) {
1166 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1167 enableHardwareVsync();
1168 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001169 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001170 }
1171 }
1172
Dan Stozab90cf072015-03-05 11:05:59 -08001173 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001174 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001175 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176 enableHardwareVsync();
1177 }
1178 }
1179
Pablo Ceballos40845df2016-01-25 17:41:15 -08001180 mFenceTracker.addFrame(refreshStartTime, presentFence,
1181 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1182
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001183 if (mAnimCompositionPending) {
1184 mAnimCompositionPending = false;
1185
Jesse Halla9a1b002013-02-27 16:39:25 -08001186 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001187 mAnimFrameTracker.setActualPresentFence(presentFence);
1188 } else {
1189 // The HWC doesn't support present fences, so use the refresh
1190 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001191 nsecs_t presentTime =
1192 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001193 mAnimFrameTracker.setActualPresentTime(presentTime);
1194 }
1195 mAnimFrameTracker.advanceFrame();
1196 }
Dan Stozab90cf072015-03-05 11:05:59 -08001197
1198 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1199 return;
1200 }
1201
1202 nsecs_t currentTime = systemTime();
1203 if (mHasPoweredOff) {
1204 mHasPoweredOff = false;
1205 } else {
1206 nsecs_t period = mPrimaryDispSync.getPeriod();
1207 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1208 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1209 if (numPeriods < NUM_BUCKETS - 1) {
1210 mFrameBuckets[numPeriods] += elapsedTime;
1211 } else {
1212 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1213 }
1214 mTotalTime += elapsedTime;
1215 }
1216 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001217}
1218
1219void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 ATRACE_CALL();
1221 ALOGV("rebuildLayerStacks");
1222
Mathias Agopiancd60f992012-08-16 16:28:27 -07001223 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001224 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001225 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001226 mVisibleRegionsDirty = false;
1227 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001228
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001229 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001230 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001231 Region opaqueRegion;
1232 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 Vector<sp<Layer>> layersSortedByZ;
1234 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1235 const Transform& tr(displayDevice->getTransform());
1236 const Rect bounds(displayDevice->getBounds());
1237 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001238 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001239 displayDevice->getLayerStack(), dirtyRegion,
1240 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001241
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001242 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001243 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001244 const sp<Layer>& layer(layers[i]);
1245 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001246 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001247 Region drawRegion(tr.transform(
1248 layer->visibleNonTransparentRegion));
1249 drawRegion.andSelf(bounds);
1250 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001251 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001252 } else {
1253 // Clear out the HWC layer if this layer was
1254 // previously visible, but no longer is
1255 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1256 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001257 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001258 }
1259 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001260 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001261 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1262 displayDevice->undefinedRegion.set(bounds);
1263 displayDevice->undefinedRegion.subtractSelf(
1264 tr.transform(opaqueRegion));
1265 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001266 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001267 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001268}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001269
Mathias Agopiancd60f992012-08-16 16:28:27 -07001270void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001271 ATRACE_CALL();
1272 ALOGV("setUpHWComposer");
1273
Jesse Hall028dc8f2013-08-20 16:35:32 -07001274 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001275 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1276 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1277 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1278
1279 // If nothing has changed (!dirty), don't recompose.
1280 // If something changed, but we don't currently have any visible layers,
1281 // and didn't when we last did a composition, then skip it this time.
1282 // The second rule does two things:
1283 // - When all layers are removed from a display, we'll emit one black
1284 // frame, then nothing more until we get new layers.
1285 // - When a display is created with a private layer stack, we won't
1286 // emit any black frames until a layer is added to the layer stack.
1287 bool mustRecompose = dirty && !(empty && wasEmpty);
1288
1289 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1290 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1291 mustRecompose ? "doing" : "skipping",
1292 dirty ? "+" : "-",
1293 empty ? "+" : "-",
1294 wasEmpty ? "+" : "-");
1295
Dan Stoza71433162014-02-04 16:22:36 -08001296 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001297
1298 if (mustRecompose) {
1299 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1300 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001301 }
1302
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 // build the h/w work list
1304 if (CC_UNLIKELY(mGeometryInvalid)) {
1305 mGeometryInvalid = false;
1306 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1307 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1308 const auto hwcId = displayDevice->getHwcDisplayId();
1309 if (hwcId >= 0) {
1310 const Vector<sp<Layer>>& currentLayers(
1311 displayDevice->getVisibleLayersSortedByZ());
1312 bool foundLayerWithoutHwc = false;
1313 for (auto& layer : currentLayers) {
1314 if (!layer->hasHwcLayer(hwcId)) {
1315 auto hwcLayer = mHwc->createLayer(hwcId);
1316 if (hwcLayer) {
1317 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1318 } else {
1319 layer->forceClientComposition(hwcId);
1320 foundLayerWithoutHwc = true;
1321 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001322 }
1323 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001324
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001326 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001327 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001328 }
1329 }
1330 }
1331 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001332 }
Riley Andrews03414a12014-07-01 14:22:59 -07001333
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001334
1335 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1336
Dan Stoza9e56aa02015-11-02 13:00:03 -08001337 // Set the per-frame data
1338 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1339 auto& displayDevice = mDisplays[displayId];
1340 const auto hwcId = displayDevice->getHwcDisplayId();
1341 if (hwcId < 0) {
1342 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001343 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001344 if (colorMatrix != mPreviousColorMatrix) {
1345 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1346 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1347 "display %zd: %d", displayId, result);
1348 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1350 layer->setPerFrameData(displayDevice);
1351 }
1352 }
1353
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001354 mPreviousColorMatrix = colorMatrix;
1355
Dan Stoza9e56aa02015-11-02 13:00:03 -08001356 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001357 auto& displayDevice = mDisplays[displayId];
1358 if (!displayDevice->isDisplayOn()) {
1359 continue;
1360 }
1361
1362 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001363 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1364 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001365 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001366}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001367
Mathias Agopiancd60f992012-08-16 16:28:27 -07001368void SurfaceFlinger::doComposition() {
1369 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001370 ALOGV("doComposition");
1371
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001372 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001373 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001374 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001375 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001376 // transform the dirty region into this screen's coordinate space
1377 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001378
1379 // repaint the framebuffer (if needed)
1380 doDisplayComposition(hw, dirtyRegion);
1381
Mathias Agopiancd60f992012-08-16 16:28:27 -07001382 hw->dirtyRegion.clear();
1383 hw->flip(hw->swapRegion);
1384 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001385 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001387 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388}
1389
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001390void SurfaceFlinger::postFramebuffer()
1391{
Mathias Agopian841cde52012-03-01 15:44:37 -08001392 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001393 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001394
Mathias Agopiana44b0412011-10-16 18:46:35 -07001395 const nsecs_t now = systemTime();
1396 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001397
Dan Stoza9e56aa02015-11-02 13:00:03 -08001398 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1399 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001400 if (!displayDevice->isDisplayOn()) {
1401 continue;
1402 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001403 const auto hwcId = displayDevice->getHwcDisplayId();
1404 if (hwcId >= 0) {
1405 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001406 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001407 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001408 if (displayId == 0) {
1409 // Make the default display current because the VirtualDisplayDevice
1410 // code cannot deal with dequeueBuffer() being called outside of the
1411 // composition loop; however the code below can call glFlush() which
1412 // is allowed to (and does in some case) call dequeueBuffer().
1413 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1414 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001415 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1416 sp<Fence> releaseFence = Fence::NO_FENCE;
1417 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1418 releaseFence = displayDevice->getClientTargetAcquireFence();
1419 } else {
1420 auto hwcLayer = layer->getHwcLayer(hwcId);
1421 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001422 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001423 layer->onLayerDisplayed(releaseFence);
1424 }
1425 if (hwcId >= 0) {
1426 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001427 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001428 }
1429
Mathias Agopiana44b0412011-10-16 18:46:35 -07001430 mLastSwapBufferTime = systemTime() - now;
1431 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001432
1433 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1434 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1435 logFrameStats();
1436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001437}
1438
Mathias Agopian87baae12012-07-31 12:38:26 -07001439void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001440{
Mathias Agopian841cde52012-03-01 15:44:37 -08001441 ATRACE_CALL();
1442
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001443 // here we keep a copy of the drawing state (that is the state that's
1444 // going to be overwritten by handleTransactionLocked()) outside of
1445 // mStateLock so that the side-effects of the State assignment
1446 // don't happen with mStateLock held (which can cause deadlocks).
1447 State drawingState(mDrawingState);
1448
Mathias Agopianca4d3602011-05-19 15:38:14 -07001449 Mutex::Autolock _l(mStateLock);
1450 const nsecs_t now = systemTime();
1451 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452
Mathias Agopianca4d3602011-05-19 15:38:14 -07001453 // Here we're guaranteed that some transaction flags are set
1454 // so we can call handleTransactionLocked() unconditionally.
1455 // We call getTransactionFlags(), which will also clear the flags,
1456 // with mStateLock held to guarantee that mCurrentState won't change
1457 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001458
Mathias Agopiane57f2922012-08-09 16:29:12 -07001459 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001460 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001461
Mathias Agopianca4d3602011-05-19 15:38:14 -07001462 mLastTransactionTime = systemTime() - now;
1463 mDebugInTransaction = 0;
1464 invalidateHwcGeometry();
1465 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001466}
1467
Mathias Agopian87baae12012-07-31 12:38:26 -07001468void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001469{
1470 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001471 const size_t count = currentLayers.size();
1472
Dan Stoza7dde5992015-05-22 09:51:44 -07001473 // Notify all layers of available frames
1474 for (size_t i = 0; i < count; ++i) {
1475 currentLayers[i]->notifyAvailableFrames();
1476 }
1477
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001478 /*
1479 * Traversal of the children
1480 * (perform the transaction for each of them if needed)
1481 */
1482
Mathias Agopian3559b072012-08-15 13:46:03 -07001483 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001484 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001485 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001486 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1487 if (!trFlags) continue;
1488
1489 const uint32_t flags = layer->doTransaction(0);
1490 if (flags & Layer::eVisibleRegion)
1491 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001492 }
1493 }
1494
1495 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001496 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001497 */
1498
Mathias Agopiane57f2922012-08-09 16:29:12 -07001499 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001500 // here we take advantage of Vector's copy-on-write semantics to
1501 // improve performance by skipping the transaction entirely when
1502 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001503 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1504 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001505 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001507 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001508 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001509
1510 // find the displays that were removed
1511 // (ie: in drawing state but not in current state)
1512 // also handle displays that changed
1513 // (ie: displays that are in both lists)
1514 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001515 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1516 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001517 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001518 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001519 // Call makeCurrent() on the primary display so we can
1520 // be sure that nothing associated with this display
1521 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001522 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001523 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001524 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1525 if (hw != NULL)
1526 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001527 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001528 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001529 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001530 } else {
1531 ALOGW("trying to remove the main display");
1532 }
1533 } else {
1534 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001535 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001536 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001537 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1538 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001539 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001540 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001541 // recreating the DisplayDevice, so we just remove it
1542 // from the drawing state, so that it get re-added
1543 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001544 sp<DisplayDevice> hw(getDisplayDevice(display));
1545 if (hw != NULL)
1546 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001547 mDisplays.removeItem(display);
1548 mDrawingState.displays.removeItemsAt(i);
1549 dc--; i--;
1550 // at this point we must loop to the next item
1551 continue;
1552 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001553
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001554 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001555 if (disp != NULL) {
1556 if (state.layerStack != draw[i].layerStack) {
1557 disp->setLayerStack(state.layerStack);
1558 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001559 if ((state.orientation != draw[i].orientation)
1560 || (state.viewport != draw[i].viewport)
1561 || (state.frame != draw[i].frame))
1562 {
1563 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001564 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001565 }
Michael Lentine47e45402014-07-18 15:34:25 -07001566 if (state.width != draw[i].width || state.height != draw[i].height) {
1567 disp->setDisplaySize(state.width, state.height);
1568 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001569 }
1570 }
1571 }
1572
1573 // find displays that were added
1574 // (ie: in current state but not in drawing state)
1575 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001576 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001577 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001578
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001579 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001580 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001581 sp<IGraphicBufferProducer> bqProducer;
1582 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001583 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1584 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001585
Dan Stoza9e56aa02015-11-02 13:00:03 -08001586 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001587 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001588 // Virtual displays without a surface are dormant:
1589 // they have external state (layer stack, projection,
1590 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001591 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001592
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001593 if (mUseHwcVirtualDisplays) {
1594 int width = 0;
1595 int status = state.surface->query(
1596 NATIVE_WINDOW_WIDTH, &width);
1597 ALOGE_IF(status != NO_ERROR,
1598 "Unable to query width (%d)", status);
1599 int height = 0;
1600 status = state.surface->query(
1601 NATIVE_WINDOW_HEIGHT, &height);
1602 ALOGE_IF(status != NO_ERROR,
1603 "Unable to query height (%d)", status);
1604 int intFormat = 0;
1605 status = state.surface->query(
1606 NATIVE_WINDOW_FORMAT, &intFormat);
1607 ALOGE_IF(status != NO_ERROR,
1608 "Unable to query format (%d)", status);
1609 auto format = static_cast<android_pixel_format_t>(
1610 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001611
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001612 mHwc->allocateVirtualDisplay(width, height, &format,
1613 &hwcId);
1614 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001615
Dan Stoza5cf424b2016-05-20 14:02:39 -07001616 // TODO: Plumb requested format back up to consumer
1617
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 sp<VirtualDisplaySurface> vds =
1619 new VirtualDisplaySurface(*mHwc,
1620 hwcId, state.surface, bqProducer,
1621 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001622
1623 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001624 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001625 }
1626 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001627 ALOGE_IF(state.surface!=NULL,
1628 "adding a supported display, but rendering "
1629 "surface is provided (%p), ignoring it",
1630 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1632 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1633 dispSurface = new FramebufferSurface(*mHwc,
1634 DisplayDevice::DISPLAY_EXTERNAL,
1635 bqConsumer);
1636 producer = bqProducer;
1637 } else {
1638 ALOGE("Attempted to add non-external non-virtual"
1639 " display");
1640 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001641 }
1642
1643 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001644 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001645 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 state.type, hwcId, state.isSecure, display,
1647 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001648 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001649 hw->setLayerStack(state.layerStack);
1650 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001651 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001652 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001653 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001654 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001655 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001656 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001657 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001658 }
1659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001660 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001662
Mathias Agopian84300952012-11-21 16:02:13 -08001663 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1664 // The transform hint might have changed for some layers
1665 // (either because a display has changed, or because a layer
1666 // as changed).
1667 //
1668 // Walk through all the layers in currentLayers,
1669 // and update their transform hint.
1670 //
1671 // If a layer is visible only on a single display, then that
1672 // display is used to calculate the hint, otherwise we use the
1673 // default display.
1674 //
1675 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1676 // the hint is set before we acquire a buffer from the surface texture.
1677 //
1678 // NOTE: layer transactions have taken place already, so we use their
1679 // drawing state. However, SurfaceFlinger's own transaction has not
1680 // happened yet, so we must use the current state layer list
1681 // (soon to become the drawing state list).
1682 //
1683 sp<const DisplayDevice> disp;
1684 uint32_t currentlayerStack = 0;
1685 for (size_t i=0; i<count; i++) {
1686 // NOTE: we rely on the fact that layers are sorted by
1687 // layerStack first (so we don't have to traverse the list
1688 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001689 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001690 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001691 if (i==0 || currentlayerStack != layerStack) {
1692 currentlayerStack = layerStack;
1693 // figure out if this layerstack is mirrored
1694 // (more than one display) if so, pick the default display,
1695 // if not, pick the only display it's on.
1696 disp.clear();
1697 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1698 sp<const DisplayDevice> hw(mDisplays[dpy]);
1699 if (hw->getLayerStack() == currentlayerStack) {
1700 if (disp == NULL) {
1701 disp = hw;
1702 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001703 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001704 break;
1705 }
1706 }
1707 }
1708 }
Chet Haase91d25932013-04-11 15:24:55 -07001709 if (disp == NULL) {
1710 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1711 // redraw after transform hint changes. See bug 8508397.
1712
1713 // could be null when this layer is using a layerStack
1714 // that is not visible on any display. Also can occur at
1715 // screen off/on times.
1716 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001717 }
Chet Haase91d25932013-04-11 15:24:55 -07001718 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001719 }
1720 }
1721
1722
Mathias Agopian3559b072012-08-15 13:46:03 -07001723 /*
1724 * Perform our own transaction if needed
1725 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001726
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001727 const LayerVector& layers(mDrawingState.layersSortedByZ);
1728 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001729 // layers have been added
1730 mVisibleRegionsDirty = true;
1731 }
1732
1733 // some layers might have been removed, so
1734 // we need to update the regions they're exposing.
1735 if (mLayersRemoved) {
1736 mLayersRemoved = false;
1737 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001738 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001739 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001740 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001741 if (currentLayers.indexOf(layer) < 0) {
1742 // this layer is not visible anymore
1743 // TODO: we could traverse the tree from front to back and
1744 // compute the actual visible region
1745 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001746 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001747 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001748 Region(Rect(s.active.w, s.active.h)));
1749 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001752 }
1753
1754 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001755
1756 updateCursorAsync();
1757}
1758
1759void SurfaceFlinger::updateCursorAsync()
1760{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001761 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1762 auto& displayDevice = mDisplays[displayId];
1763 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001764 continue;
1765 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001766
1767 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1768 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001769 }
1770 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001771}
1772
1773void SurfaceFlinger::commitTransaction()
1774{
1775 if (!mLayersPendingRemoval.isEmpty()) {
1776 // Notify removed layers now that they can't be drawn from
1777 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001778 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1779 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001780 mLayersPendingRemoval[i]->onRemoved();
1781 }
1782 mLayersPendingRemoval.clear();
1783 }
1784
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001785 // If this transaction is part of a window animation then the next frame
1786 // we composite should be considered an animation as well.
1787 mAnimCompositionPending = mAnimTransactionPending;
1788
Mathias Agopian4fec8732012-06-29 14:12:52 -07001789 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001790 mTransactionPending = false;
1791 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001792 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001793}
1794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001796 const LayerVector& currentLayers, uint32_t layerStack,
1797 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001798{
Mathias Agopian841cde52012-03-01 15:44:37 -08001799 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001801
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802 Region aboveOpaqueLayers;
1803 Region aboveCoveredLayers;
1804 Region dirty;
1805
Mathias Agopian87baae12012-07-31 12:38:26 -07001806 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807
1808 size_t i = currentLayers.size();
1809 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001810 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811
1812 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001813 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814
Jesse Hall01e29052013-02-19 16:13:35 -08001815 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001816 if (s.layerStack != layerStack)
1817 continue;
1818
Mathias Agopianab028732010-03-16 16:41:46 -07001819 /*
1820 * opaqueRegion: area of a surface that is fully opaque.
1821 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001822 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001823
1824 /*
1825 * visibleRegion: area of a surface that is visible on screen
1826 * and not fully transparent. This is essentially the layer's
1827 * footprint minus the opaque regions above it.
1828 * Areas covered by a translucent surface are considered visible.
1829 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001830 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001831
1832 /*
1833 * coveredRegion: area of a surface that is covered by all
1834 * visible regions above it (which includes the translucent areas).
1835 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001836 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001837
Jesse Halla8026d22012-09-25 13:25:04 -07001838 /*
1839 * transparentRegion: area of a surface that is hinted to be completely
1840 * transparent. This is only used to tell when the layer has no visible
1841 * non-transparent regions and can be removed from the layer list. It
1842 * does not affect the visibleRegion of this layer or any layers
1843 * beneath it. The hint may not be correct if apps don't respect the
1844 * SurfaceView restrictions (which, sadly, some don't).
1845 */
1846 Region transparentRegion;
1847
Mathias Agopianab028732010-03-16 16:41:46 -07001848
1849 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001850 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001851 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001852 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001854 if (!visibleRegion.isEmpty()) {
1855 // Remove the transparent area from the visible region
1856 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001857 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001858 if (tr.preserveRects()) {
1859 // transform the transparent region
1860 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001861 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001862 // transformation too complex, can't do the
1863 // transparent region optimization.
1864 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001865 }
Mathias Agopianab028732010-03-16 16:41:46 -07001866 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001867
Mathias Agopianab028732010-03-16 16:41:46 -07001868 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001869 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001870 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001871 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1872 // the opaque region is the layer's footprint
1873 opaqueRegion = visibleRegion;
1874 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875 }
1876 }
1877
Mathias Agopianab028732010-03-16 16:41:46 -07001878 // Clip the covered region to the visible region
1879 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1880
1881 // Update aboveCoveredLayers for next (lower) layer
1882 aboveCoveredLayers.orSelf(visibleRegion);
1883
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001884 // subtract the opaque region covered by the layers above us
1885 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886
1887 // compute this layer's dirty region
1888 if (layer->contentDirty) {
1889 // we need to invalidate the whole region
1890 dirty = visibleRegion;
1891 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001892 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 layer->contentDirty = false;
1894 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001895 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001896 * the exposed region consists of two components:
1897 * 1) what's VISIBLE now and was COVERED before
1898 * 2) what's EXPOSED now less what was EXPOSED before
1899 *
1900 * note that (1) is conservative, we start with the whole
1901 * visible region but only keep what used to be covered by
1902 * something -- which mean it may have been exposed.
1903 *
1904 * (2) handles areas that were not covered by anything but got
1905 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001906 */
Mathias Agopianab028732010-03-16 16:41:46 -07001907 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001908 const Region oldVisibleRegion = layer->visibleRegion;
1909 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001910 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1911 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001912 }
1913 dirty.subtractSelf(aboveOpaqueLayers);
1914
1915 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001916 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001917
Mathias Agopianab028732010-03-16 16:41:46 -07001918 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001919 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001920
Jesse Halla8026d22012-09-25 13:25:04 -07001921 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001922 layer->setVisibleRegion(visibleRegion);
1923 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001924 layer->setVisibleNonTransparentRegion(
1925 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926 }
1927
Mathias Agopian87baae12012-07-31 12:38:26 -07001928 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929}
1930
Mathias Agopian87baae12012-07-31 12:38:26 -07001931void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1932 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001933 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001934 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1935 if (hw->getLayerStack() == layerStack) {
1936 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001937 }
1938 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001939}
1940
Dan Stoza6b9454d2014-11-07 16:00:59 -08001941bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001942{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 ALOGV("handlePageFlip");
1944
Mathias Agopian4fec8732012-06-29 14:12:52 -07001945 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001946
Mathias Agopian4fec8732012-06-29 14:12:52 -07001947 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001948 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001949 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001950
1951 // Store the set of layers that need updates. This set must not change as
1952 // buffers are being latched, as this could result in a deadlock.
1953 // Example: Two producers share the same command stream and:
1954 // 1.) Layer 0 is latched
1955 // 2.) Layer 0 gets a new frame
1956 // 2.) Layer 1 gets a new frame
1957 // 3.) Layer 1 is latched.
1958 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1959 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001960 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001961 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001962 if (layer->hasQueuedFrame()) {
1963 frameQueued = true;
1964 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001966 } else {
1967 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001968 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001969 } else {
1970 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001971 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001972 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001974 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001975 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001976 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001977 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001978 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001979
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001980 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001981
1982 // If we will need to wake up at some time in the future to deal with a
1983 // queued frame that shouldn't be displayed during this vsync period, wake
1984 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001986 signalLayerUpdate();
1987 }
1988
1989 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001991}
1992
Mathias Agopianad456f92011-01-13 17:53:01 -08001993void SurfaceFlinger::invalidateHwcGeometry()
1994{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001996}
1997
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001998
Mathias Agopiancd60f992012-08-16 16:28:27 -07001999void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002000 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002001{
Dan Stoza71433162014-02-04 16:22:36 -08002002 // We only need to actually compose the display if:
2003 // 1) It is being handled by hardware composer, which may need this to
2004 // keep its virtual display state machine in sync, or
2005 // 2) There is work to be done (the dirty region isn't empty)
2006 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2007 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002009 return;
2010 }
2011
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ALOGV("doDisplayComposition");
2013
Mathias Agopian87baae12012-07-31 12:38:26 -07002014 Region dirtyRegion(inDirtyRegion);
2015
Mathias Agopianb8a55602009-06-26 19:06:36 -07002016 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002017 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018
Mathias Agopian42977342012-08-05 00:40:46 -07002019 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002020 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002021 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2022 // takes a rectangle, we must make sure to update that whole
2023 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002024 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002025 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002026 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002027 // We need to redraw the rectangle that will be updated
2028 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002029 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002030 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002031 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002032 } else {
2033 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002034 dirtyRegion.set(hw->bounds());
2035 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036 }
2037 }
2038
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002039 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002041 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002042 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002043
2044 // swap buffers (presentation)
2045 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002046}
2047
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048bool SurfaceFlinger::doComposeSurfaces(
2049 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002050{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002052
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002054
2055 mat4 oldColorMatrix;
2056 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2057 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2058 if (applyColorMatrix) {
2059 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2060 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2061 }
2062
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2064 if (hasClientComposition) {
2065 ALOGV("hasClientComposition");
2066
2067 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002068 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002070 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2071 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2072 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2073 }
2074 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002075 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002076
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002077 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2079 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002080 // when using overlays, we assume a fully transparent framebuffer
2081 // NOTE: we could reduce how much we need to clear, for instance
2082 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002083 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002084 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002086 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002087 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002088 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002089
2090 // we remove the scissor part
2091 // we're left with the letterbox region
2092 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002094
2095 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002097
2098 // but limit it to the dirty region
2099 region.andSelf(dirty);
2100
Mathias Agopianb9494d52012-04-18 02:28:45 -07002101 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002102 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002103 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002105 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002106 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002107
Dan Stoza9e56aa02015-11-02 13:00:03 -08002108 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002109 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002110 // scissor on the main display. It should never be needed
2111 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 const Rect& bounds(displayDevice->getBounds());
2113 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002114 if (scissor != bounds) {
2115 // scissor doesn't match the screen's dimensions, so we
2116 // need to clear everything outside of it and enable
2117 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002118
Mathias Agopianf45c5102012-10-24 16:29:17 -07002119 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 const uint32_t height = displayDevice->getHeight();
2121 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002122 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002123 }
2124 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002125 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002126
Mathias Agopian85d751c2012-08-29 16:59:24 -07002127 /*
2128 * and then, render the layers targeted at the framebuffer
2129 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002130
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 ALOGV("Rendering client layers");
2132 const Transform& displayTransform = displayDevice->getTransform();
2133 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002134 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 bool firstLayer = true;
2136 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2137 const Region clip(dirty.intersect(
2138 displayTransform.transform(layer->visibleRegion)));
2139 ALOGV("Layer: %s", layer->getName().string());
2140 ALOGV(" Composition type: %s",
2141 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002142 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002143 switch (layer->getCompositionType(hwcId)) {
2144 case HWC2::Composition::Cursor:
2145 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002146 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002148 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002149 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2150 layer->isOpaque(state) && (state.alpha == 1.0f)
2151 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002152 // never clear the very first layer since we're
2153 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002154 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002155 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002156 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002157 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002158 case HWC2::Composition::Client: {
2159 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002160 break;
2161 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002163 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002164 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002165 } else {
2166 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002167 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002169 }
2170 } else {
2171 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002173 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002174 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002175 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002177 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002178 }
2179 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002180
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002181 if (applyColorMatrix) {
2182 getRenderEngine().setupColorTransform(oldColorMatrix);
2183 }
2184
Mathias Agopianf45c5102012-10-24 16:29:17 -07002185 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002186 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002187 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002188}
2189
Mathias Agopian3f844832013-08-07 21:24:32 -07002190void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002191 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002192 RenderEngine& engine(getRenderEngine());
2193 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194}
2195
Dan Stoza7d89d062015-04-30 13:29:25 -07002196status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002197 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002198 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002199 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002200{
Dan Stoza7d89d062015-04-30 13:29:25 -07002201 // add this layer to the current state list
2202 {
2203 Mutex::Autolock _l(mStateLock);
2204 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2205 return NO_MEMORY;
2206 }
2207 mCurrentState.layersSortedByZ.add(lbc);
2208 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2209 }
2210
Mathias Agopian96f08192010-06-02 23:28:45 -07002211 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002212 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002213
Dan Stoza7d89d062015-04-30 13:29:25 -07002214 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002215}
2216
Dan Stoza92cd24e2016-08-09 13:21:03 -07002217status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002218 Mutex::Autolock _l(mStateLock);
Dan Stoza92cd24e2016-08-09 13:21:03 -07002219 sp<Layer> layer = weakLayer.promote();
2220 if (layer == nullptr) {
2221 // The layer has already been removed, carry on
2222 return NO_ERROR;
2223 }
2224
Mathias Agopian13127d82013-03-05 17:47:11 -08002225 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002227 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002228 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002229 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002230 return NO_ERROR;
2231 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002232 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233}
2234
Dan Stozac7014012014-02-14 15:03:43 -08002235uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002236 return android_atomic_release_load(&mTransactionFlags);
2237}
2238
Mathias Agopian3f844832013-08-07 21:24:32 -07002239uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2241}
2242
Mathias Agopian3f844832013-08-07 21:24:32 -07002243uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2245 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002246 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247 }
2248 return old;
2249}
2250
Mathias Agopian8b33f032012-07-24 20:43:54 -07002251void SurfaceFlinger::setTransactionState(
2252 const Vector<ComposerState>& state,
2253 const Vector<DisplayState>& displays,
2254 uint32_t flags)
2255{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002256 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002257 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002258 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002259
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002260 if (flags & eAnimation) {
2261 // For window updates that are part of an animation we must wait for
2262 // previous animation "frames" to be handled.
2263 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002264 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002265 if (CC_UNLIKELY(err != NO_ERROR)) {
2266 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002267 // caller after a few seconds.
2268 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2269 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002270 mAnimTransactionPending = false;
2271 break;
2272 }
2273 }
2274 }
2275
Mathias Agopiane57f2922012-08-09 16:29:12 -07002276 size_t count = displays.size();
2277 for (size_t i=0 ; i<count ; i++) {
2278 const DisplayState& s(displays[i]);
2279 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002280 }
2281
Mathias Agopiane57f2922012-08-09 16:29:12 -07002282 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002283 for (size_t i=0 ; i<count ; i++) {
2284 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002285 // Here we need to check that the interface we're given is indeed
2286 // one of our own. A malicious client could give us a NULL
2287 // IInterface, or one of its own or even one of our own but a
2288 // different type. All these situations would cause us to crash.
2289 //
2290 // NOTE: it would be better to use RTTI as we could directly check
2291 // that we have a Client*. however, RTTI is disabled in Android.
2292 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002293 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002294 if (binder != NULL) {
2295 String16 desc(binder->getInterfaceDescriptor());
2296 if (desc == ISurfaceComposerClient::descriptor) {
2297 sp<Client> client( static_cast<Client *>(s.client.get()) );
2298 transactionFlags |= setClientStateLocked(client, s.state);
2299 }
2300 }
2301 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002302 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002303
Robert Carr2a7dbb42016-05-24 11:41:28 -07002304 // If a synchronous transaction is explicitly requested without any changes,
2305 // force a transaction anyway. This can be used as a flush mechanism for
2306 // previous async transactions.
2307 if (transactionFlags == 0 && (flags & eSynchronous)) {
2308 transactionFlags = eTransactionNeeded;
2309 }
2310
Mathias Agopian386aa982011-11-07 21:58:03 -08002311 if (transactionFlags) {
2312 // this triggers the transaction
2313 setTransactionFlags(transactionFlags);
2314
2315 // if this is a synchronous transaction, wait for it to take effect
2316 // before returning.
2317 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002318 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002319 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002320 if (flags & eAnimation) {
2321 mAnimTransactionPending = true;
2322 }
2323 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002324 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2325 if (CC_UNLIKELY(err != NO_ERROR)) {
2326 // just in case something goes wrong in SF, return to the
2327 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002328 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2329 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002330 break;
2331 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002332 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 }
2334}
2335
Mathias Agopiane57f2922012-08-09 16:29:12 -07002336uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2337{
Jesse Hall9a143922012-10-04 16:29:19 -07002338 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2339 if (dpyIdx < 0)
2340 return 0;
2341
Mathias Agopiane57f2922012-08-09 16:29:12 -07002342 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002343 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002344 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002345 const uint32_t what = s.what;
2346 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002347 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002348 disp.surface = s.surface;
2349 flags |= eDisplayTransactionNeeded;
2350 }
2351 }
2352 if (what & DisplayState::eLayerStackChanged) {
2353 if (disp.layerStack != s.layerStack) {
2354 disp.layerStack = s.layerStack;
2355 flags |= eDisplayTransactionNeeded;
2356 }
2357 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002358 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002359 if (disp.orientation != s.orientation) {
2360 disp.orientation = s.orientation;
2361 flags |= eDisplayTransactionNeeded;
2362 }
2363 if (disp.frame != s.frame) {
2364 disp.frame = s.frame;
2365 flags |= eDisplayTransactionNeeded;
2366 }
2367 if (disp.viewport != s.viewport) {
2368 disp.viewport = s.viewport;
2369 flags |= eDisplayTransactionNeeded;
2370 }
2371 }
Michael Lentine47e45402014-07-18 15:34:25 -07002372 if (what & DisplayState::eDisplaySizeChanged) {
2373 if (disp.width != s.width) {
2374 disp.width = s.width;
2375 flags |= eDisplayTransactionNeeded;
2376 }
2377 if (disp.height != s.height) {
2378 disp.height = s.height;
2379 flags |= eDisplayTransactionNeeded;
2380 }
2381 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002382 }
2383 return flags;
2384}
2385
2386uint32_t SurfaceFlinger::setClientStateLocked(
2387 const sp<Client>& client,
2388 const layer_state_t& s)
2389{
2390 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002391 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002392 if (layer != 0) {
2393 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002394 bool geometryAppliesWithResize =
2395 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002396 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002397 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002398 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002399 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 }
2401 if (what & layer_state_t::eLayerChanged) {
2402 // NOTE: index needs to be calculated before we update the state
2403 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002404 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002405 mCurrentState.layersSortedByZ.removeAt(idx);
2406 mCurrentState.layersSortedByZ.add(layer);
2407 // we need traversal (state changed)
2408 // AND transaction (list changed)
2409 flags |= eTransactionNeeded|eTraversalNeeded;
2410 }
2411 }
2412 if (what & layer_state_t::eSizeChanged) {
2413 if (layer->setSize(s.w, s.h)) {
2414 flags |= eTraversalNeeded;
2415 }
2416 }
2417 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002419 flags |= eTraversalNeeded;
2420 }
2421 if (what & layer_state_t::eMatrixChanged) {
2422 if (layer->setMatrix(s.matrix))
2423 flags |= eTraversalNeeded;
2424 }
2425 if (what & layer_state_t::eTransparentRegionChanged) {
2426 if (layer->setTransparentRegionHint(s.transparentRegion))
2427 flags |= eTraversalNeeded;
2428 }
Dan Stoza23116082015-06-18 14:58:39 -07002429 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002430 if (layer->setFlags(s.flags, s.mask))
2431 flags |= eTraversalNeeded;
2432 }
2433 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002434 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002435 flags |= eTraversalNeeded;
2436 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002437 if (what & layer_state_t::eFinalCropChanged) {
2438 if (layer->setFinalCrop(s.finalCrop))
2439 flags |= eTraversalNeeded;
2440 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002441 if (what & layer_state_t::eLayerStackChanged) {
2442 // NOTE: index needs to be calculated before we update the state
2443 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002444 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002445 mCurrentState.layersSortedByZ.removeAt(idx);
2446 mCurrentState.layersSortedByZ.add(layer);
2447 // we need traversal (state changed)
2448 // AND transaction (list changed)
2449 flags |= eTransactionNeeded|eTraversalNeeded;
2450 }
2451 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002452 if (what & layer_state_t::eDeferTransaction) {
2453 layer->deferTransactionUntil(s.handle, s.frameNumber);
2454 // We don't trigger a traversal here because if no other state is
2455 // changed, we don't want this to cause any more work
2456 }
Robert Carrc3574f72016-03-24 12:19:32 -07002457 if (what & layer_state_t::eOverrideScalingModeChanged) {
2458 layer->setOverrideScalingMode(s.overrideScalingMode);
2459 // We don't trigger a traversal here because if no other state is
2460 // changed, we don't want this to cause any more work
2461 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002462 }
2463 return flags;
2464}
2465
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002466status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002467 const String8& name,
2468 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002469 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2470 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002471{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002472 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002473 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002474 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002475 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002476 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002477 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002478
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002479 status_t result = NO_ERROR;
2480
2481 sp<Layer> layer;
2482
Mathias Agopian3165cc22012-08-08 19:42:09 -07002483 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2484 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002485 result = createNormalLayer(client,
2486 name, w, h, flags, format,
2487 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002489 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002490 result = createDimLayer(client,
2491 name, w, h, flags,
2492 handle, gbp, &layer);
2493 break;
2494 default:
2495 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 break;
2497 }
2498
Dan Stoza7d89d062015-04-30 13:29:25 -07002499 if (result != NO_ERROR) {
2500 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002502
2503 result = addClientLayer(client, *handle, *gbp, layer);
2504 if (result != NO_ERROR) {
2505 return result;
2506 }
2507
2508 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002509 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510}
2511
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002512status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2513 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2514 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515{
2516 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002517 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518 case PIXEL_FORMAT_TRANSPARENT:
2519 case PIXEL_FORMAT_TRANSLUCENT:
2520 format = PIXEL_FORMAT_RGBA_8888;
2521 break;
2522 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002523 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 break;
2525 }
2526
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002527 *outLayer = new Layer(this, client, name, w, h, flags);
2528 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2529 if (err == NO_ERROR) {
2530 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002531 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002533
2534 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2535 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536}
2537
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002538status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2539 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2540 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002541{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002542 *outLayer = new LayerDim(this, client, name, w, h, flags);
2543 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002544 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002545 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002546}
2547
Mathias Agopianac9fa422013-02-11 16:40:36 -08002548status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549{
Mathias Agopian67106042013-03-14 19:18:13 -07002550 // called by the window manager when it wants to remove a Layer
2551 status_t err = NO_ERROR;
2552 sp<Layer> l(client->getLayerUser(handle));
2553 if (l != NULL) {
2554 err = removeLayer(l);
2555 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2556 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002557 }
2558 return err;
2559}
2560
Mathias Agopian13127d82013-03-05 17:47:11 -08002561status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002562{
Mathias Agopian67106042013-03-14 19:18:13 -07002563 // called by ~LayerCleaner() when all references to the IBinder (handle)
2564 // are gone
Dan Stoza92cd24e2016-08-09 13:21:03 -07002565 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566}
2567
Mathias Agopianb60314a2012-04-10 22:09:54 -07002568// ---------------------------------------------------------------------------
2569
Andy McFadden13a082e2012-08-24 10:16:42 -07002570void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002571 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002572 Vector<ComposerState> state;
2573 Vector<DisplayState> displays;
2574 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002575 d.what = DisplayState::eDisplayProjectionChanged |
2576 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002577 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002578 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002579 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002580 d.frame.makeInvalid();
2581 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002582 d.width = 0;
2583 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002584 displays.add(d);
2585 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002586 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002587
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2589 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002590 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002591}
2592
2593void SurfaceFlinger::initializeDisplays() {
2594 class MessageScreenInitialized : public MessageBase {
2595 SurfaceFlinger* flinger;
2596 public:
2597 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2598 virtual bool handler() {
2599 flinger->onInitializeDisplays();
2600 return true;
2601 }
2602 };
2603 sp<MessageBase> msg = new MessageScreenInitialized(this);
2604 postMessageAsync(msg); // we may be called from main thread, use async message
2605}
2606
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002607void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2608 int mode) {
2609 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2610 this);
2611 int32_t type = hw->getDisplayType();
2612 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002613
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002614 if (mode == currentMode) {
2615 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002616 return;
2617 }
2618
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002619 hw->setPowerMode(mode);
2620 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2621 ALOGW("Trying to set power mode for virtual display");
2622 return;
2623 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002624
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002625 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002626 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002627 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002628 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2629 // FIXME: eventthread only knows about the main display right now
2630 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002631 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002632 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002634 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002635 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002636 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002637
2638 struct sched_param param = {0};
2639 param.sched_priority = 1;
2640 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2641 ALOGW("Couldn't set SCHED_FIFO on display on");
2642 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002643 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002644 // Turn off the display
2645 struct sched_param param = {0};
2646 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2647 ALOGW("Couldn't set SCHED_OTHER on display off");
2648 }
2649
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002650 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002651 disableHardwareVsync(true); // also cancels any in-progress resync
2652
Mathias Agopiancde87a32012-09-13 14:09:01 -07002653 // FIXME: eventthread only knows about the main display right now
2654 mEventThread->onScreenReleased();
2655 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002656
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002657 getHwComposer().setPowerMode(type, mode);
2658 mVisibleRegionsDirty = true;
2659 // from this point on, SF will stop drawing on this display
2660 } else {
2661 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002662 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002663}
2664
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002665void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2666 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002667 SurfaceFlinger& mFlinger;
2668 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002669 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002670 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002671 MessageSetPowerMode(SurfaceFlinger& flinger,
2672 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2673 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002674 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002675 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002676 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002677 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002678 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002679 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002680 ALOGW("Attempt to set power mode = %d for virtual display",
2681 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002682 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002683 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002684 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002685 return true;
2686 }
2687 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002688 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002689 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002690}
2691
2692// ---------------------------------------------------------------------------
2693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002694status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2695{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002697
Mathias Agopianbd115332013-04-18 16:41:04 -07002698 IPCThreadState* ipc = IPCThreadState::self();
2699 const int pid = ipc->getCallingPid();
2700 const int uid = ipc->getCallingUid();
2701 if ((uid != AID_SHELL) &&
2702 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002703 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002704 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002706 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002707 // (this would indicate SF is stuck, but we want to be able to
2708 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002709 status_t err = mStateLock.timedLock(s2ns(1));
2710 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002711 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002712 result.appendFormat(
2713 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2714 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002715 }
2716
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002717 bool dumpAll = true;
2718 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002719 size_t numArgs = args.size();
2720 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002721 if ((index < numArgs) &&
2722 (args[index] == String16("--list"))) {
2723 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002724 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002725 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002726 }
2727
2728 if ((index < numArgs) &&
2729 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002730 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002731 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002732 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002733 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002734
2735 if ((index < numArgs) &&
2736 (args[index] == String16("--latency-clear"))) {
2737 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002738 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002739 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002740 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002741
2742 if ((index < numArgs) &&
2743 (args[index] == String16("--dispsync"))) {
2744 index++;
2745 mPrimaryDispSync.dump(result);
2746 dumpAll = false;
2747 }
Dan Stozab90cf072015-03-05 11:05:59 -08002748
2749 if ((index < numArgs) &&
2750 (args[index] == String16("--static-screen"))) {
2751 index++;
2752 dumpStaticScreenStats(result);
2753 dumpAll = false;
2754 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002755
2756 if ((index < numArgs) &&
2757 (args[index] == String16("--fences"))) {
2758 index++;
2759 mFenceTracker.dump(&result);
2760 dumpAll = false;
2761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002762 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002763
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002764 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002765 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002766 }
2767
Mathias Agopian9795c422009-08-26 16:36:26 -07002768 if (locked) {
2769 mStateLock.unlock();
2770 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002771 }
2772 write(fd, result.string(), result.size());
2773 return NO_ERROR;
2774}
2775
Dan Stozac7014012014-02-14 15:03:43 -08002776void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2777 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002778{
2779 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2780 const size_t count = currentLayers.size();
2781 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002782 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002783 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002784 }
2785}
2786
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002787void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002788 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002789{
2790 String8 name;
2791 if (index < args.size()) {
2792 name = String8(args[index]);
2793 index++;
2794 }
2795
Dan Stoza9e56aa02015-11-02 13:00:03 -08002796 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2797 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002798 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002799
2800 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002801 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002802 } else {
2803 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2804 const size_t count = currentLayers.size();
2805 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002806 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002807 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002808 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002809 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002810 }
2811 }
2812}
2813
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002814void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002815 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002816{
2817 String8 name;
2818 if (index < args.size()) {
2819 name = String8(args[index]);
2820 index++;
2821 }
2822
2823 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2824 const size_t count = currentLayers.size();
2825 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002826 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002827 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002828 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002829 }
2830 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002831
Svetoslavd85084b2014-03-20 10:28:31 -07002832 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002833}
2834
Jamie Gennis6547ff42013-07-16 20:12:42 -07002835// This should only be called from the main thread. Otherwise it would need
2836// the lock and should use mCurrentState rather than mDrawingState.
2837void SurfaceFlinger::logFrameStats() {
2838 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2839 const size_t count = drawingLayers.size();
2840 for (size_t i=0 ; i<count ; i++) {
2841 const sp<Layer>& layer(drawingLayers[i]);
2842 layer->logFrameStats();
2843 }
2844
2845 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2846}
2847
Andy McFadden4803b742012-09-24 19:07:20 -07002848/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2849{
2850 static const char* config =
2851 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002852#ifdef HAS_CONTEXT_PRIORITY
2853 " HAS_CONTEXT_PRIORITY"
2854#endif
2855#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2856 " NEVER_DEFAULT_TO_ASYNC_MODE"
2857#endif
2858#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2859 " TARGET_DISABLE_TRIPLE_BUFFERING"
2860#endif
2861 "]";
2862 result.append(config);
2863}
2864
Dan Stozab90cf072015-03-05 11:05:59 -08002865void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2866{
2867 result.appendFormat("Static screen stats:\n");
2868 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2869 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2870 float percent = 100.0f *
2871 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2872 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2873 b + 1, bucketTimeSec, percent);
2874 }
2875 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2876 float percent = 100.0f *
2877 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2878 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2879 NUM_BUCKETS - 1, bucketTimeSec, percent);
2880}
2881
Dan Stozae77c7662016-05-13 11:37:28 -07002882void SurfaceFlinger::recordBufferingStats(const char* layerName,
2883 std::vector<OccupancyTracker::Segment>&& history) {
2884 Mutex::Autolock lock(mBufferingStatsMutex);
2885 auto& stats = mBufferingStats[layerName];
2886 for (const auto& segment : history) {
2887 if (!segment.usedThirdBuffer) {
2888 stats.twoBufferTime += segment.totalTime;
2889 }
2890 if (segment.occupancyAverage < 1.0f) {
2891 stats.doubleBufferedTime += segment.totalTime;
2892 } else if (segment.occupancyAverage < 2.0f) {
2893 stats.tripleBufferedTime += segment.totalTime;
2894 }
2895 ++stats.numSegments;
2896 stats.totalTime += segment.totalTime;
2897 }
2898}
2899
2900void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2901 result.append("Buffering stats:\n");
2902 result.append(" [Layer name] <Active time> <Two buffer> "
2903 "<Double buffered> <Triple buffered>\n");
2904 Mutex::Autolock lock(mBufferingStatsMutex);
2905 typedef std::tuple<std::string, float, float, float> BufferTuple;
2906 std::map<float, BufferTuple, std::greater<float>> sorted;
2907 for (const auto& statsPair : mBufferingStats) {
2908 const char* name = statsPair.first.c_str();
2909 const BufferingStats& stats = statsPair.second;
2910 if (stats.numSegments == 0) {
2911 continue;
2912 }
2913 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2914 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2915 stats.totalTime;
2916 float doubleBufferRatio = static_cast<float>(
2917 stats.doubleBufferedTime) / stats.totalTime;
2918 float tripleBufferRatio = static_cast<float>(
2919 stats.tripleBufferedTime) / stats.totalTime;
2920 sorted.insert({activeTime, {name, twoBufferRatio,
2921 doubleBufferRatio, tripleBufferRatio}});
2922 }
2923 for (const auto& sortedPair : sorted) {
2924 float activeTime = sortedPair.first;
2925 const BufferTuple& values = sortedPair.second;
2926 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2927 std::get<0>(values).c_str(), activeTime,
2928 std::get<1>(values), std::get<2>(values),
2929 std::get<3>(values));
2930 }
2931 result.append("\n");
2932}
2933
2934
Mathias Agopian74d211a2013-04-22 16:55:35 +02002935void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2936 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002937{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002938 bool colorize = false;
2939 if (index < args.size()
2940 && (args[index] == String16("--color"))) {
2941 colorize = true;
2942 index++;
2943 }
2944
2945 Colorizer colorizer(colorize);
2946
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002947 // figure out if we're stuck somewhere
2948 const nsecs_t now = systemTime();
2949 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2950 const nsecs_t inTransaction(mDebugInTransaction);
2951 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2952 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2953
2954 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002955 * Dump library configuration.
2956 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002957
2958 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002959 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002960 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002961 appendSfConfigString(result);
2962 appendUiConfigString(result);
2963 appendGuiConfigString(result);
2964 result.append("\n");
2965
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002966 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002967 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002968 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002969 result.append(SyncFeatures::getInstance().toString());
2970 result.append("\n");
2971
Dan Stoza9e56aa02015-11-02 13:00:03 -08002972 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2973
Andy McFadden41d67d72014-04-25 16:58:34 -07002974 colorizer.bold(result);
2975 result.append("DispSync configuration: ");
2976 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002977 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2978 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002979 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2980 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002981 result.append("\n");
2982
Dan Stozab90cf072015-03-05 11:05:59 -08002983 // Dump static screen stats
2984 result.append("\n");
2985 dumpStaticScreenStats(result);
2986 result.append("\n");
2987
Dan Stozae77c7662016-05-13 11:37:28 -07002988 dumpBufferingStats(result);
2989
Andy McFadden4803b742012-09-24 19:07:20 -07002990 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002991 * Dump the visible layer list
2992 */
2993 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2994 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002995 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002996 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002997 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002998 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002999 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003000 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003001 }
3002
3003 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003004 * Dump Display state
3005 */
3006
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003007 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003008 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003009 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003010 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3011 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003012 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003013 }
3014
3015 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003016 * Dump SurfaceFlinger global state
3017 */
3018
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003019 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003020 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003021 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003022
Mathias Agopian888c8222012-08-04 21:10:38 -07003023 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003024 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003025
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003026 colorizer.bold(result);
3027 result.appendFormat("EGL implementation : %s\n",
3028 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3029 colorizer.reset(result);
3030 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003031 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003032
Mathias Agopian875d8e12013-06-07 15:35:48 -07003033 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003034
Mathias Agopian42977342012-08-05 00:40:46 -07003035 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003036 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3037 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003038 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003039 " last eglSwapBuffers() time: %f us\n"
3040 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003041 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003042 " refresh-rate : %f fps\n"
3043 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003044 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003045 " gpu_to_cpu_unsupported : %d\n"
3046 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003047 mLastSwapBufferTime/1000.0,
3048 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003049 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 1e9 / activeConfig->getVsyncPeriod(),
3051 activeConfig->getDpiX(),
3052 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003053 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003054
Mathias Agopian74d211a2013-04-22 16:55:35 +02003055 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003056 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003057
Mathias Agopian74d211a2013-04-22 16:55:35 +02003058 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003059 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003060
3061 /*
3062 * VSYNC state
3063 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003064 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003065 result.append("\n");
3066
3067 /*
3068 * HWC layer minidump
3069 */
3070 for (size_t d = 0; d < mDisplays.size(); d++) {
3071 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3072 int32_t hwcId = displayDevice->getHwcDisplayId();
3073 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3074 continue;
3075 }
3076
3077 result.appendFormat("Display %d HWC layers:\n", hwcId);
3078 Layer::miniDumpHeader(result);
3079 for (size_t l = 0; l < count; l++) {
3080 const sp<Layer>& layer(currentLayers[l]);
3081 layer->miniDump(result, hwcId);
3082 }
3083 result.append("\n");
3084 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003085
3086 /*
3087 * Dump HWComposer state
3088 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003089 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003090 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003091 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003092 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 result.appendFormat(" h/w composer %s\n",
3094 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003095 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003096
3097 /*
3098 * Dump gralloc state
3099 */
3100 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3101 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003102}
3103
Mathias Agopian13127d82013-03-05 17:47:11 -08003104const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003105SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003106 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003107 wp<IBinder> dpy;
3108 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3109 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3110 dpy = mDisplays.keyAt(i);
3111 break;
3112 }
3113 }
3114 if (dpy == NULL) {
3115 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3116 // Just use the primary display so we have something to return
3117 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3118 }
3119 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003120}
3121
Keun young Park63f165f2012-08-31 10:53:36 -07003122bool SurfaceFlinger::startDdmConnection()
3123{
3124 void* libddmconnection_dso =
3125 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3126 if (!libddmconnection_dso) {
3127 return false;
3128 }
3129 void (*DdmConnection_start)(const char* name);
3130 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003131 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003132 if (!DdmConnection_start) {
3133 dlclose(libddmconnection_dso);
3134 return false;
3135 }
3136 (*DdmConnection_start)(getServiceName());
3137 return true;
3138}
3139
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140status_t SurfaceFlinger::onTransact(
3141 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3142{
3143 switch (code) {
3144 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003145 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003146 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003148 case CLEAR_ANIMATION_FRAME_STATS:
3149 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003150 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003151 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 {
3153 // codes that require permission check
3154 IPCThreadState* ipc = IPCThreadState::self();
3155 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003156 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003157 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003158 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003159 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003160 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3161 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003163 break;
3164 }
3165 case CAPTURE_SCREEN:
3166 {
3167 // codes that require permission check
3168 IPCThreadState* ipc = IPCThreadState::self();
3169 const int pid = ipc->getCallingPid();
3170 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003171 if ((uid != AID_GRAPHICS) &&
3172 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003173 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003174 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3175 return PERMISSION_DENIED;
3176 }
3177 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 }
3179 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003180
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003181 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3182 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003183 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003184 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003185 IPCThreadState* ipc = IPCThreadState::self();
3186 const int pid = ipc->getCallingPid();
3187 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003188 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003189 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 return PERMISSION_DENIED;
3191 }
3192 int n;
3193 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003194 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003195 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 return NO_ERROR;
3197 case 1002: // SHOW_UPDATES
3198 n = data.readInt32();
3199 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003200 invalidateHwcGeometry();
3201 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003204 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003205 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003207 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003208 setTransactionFlags(
3209 eTransactionNeeded|
3210 eDisplayTransactionNeeded|
3211 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003212 return NO_ERROR;
3213 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003214 case 1006:{ // send empty update
3215 signalRefresh();
3216 return NO_ERROR;
3217 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003218 case 1008: // toggle use of hw composer
3219 n = data.readInt32();
3220 mDebugDisableHWC = n ? 1 : 0;
3221 invalidateHwcGeometry();
3222 repaintEverything();
3223 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003224 case 1009: // toggle use of transform hint
3225 n = data.readInt32();
3226 mDebugDisableTransformHint = n ? 1 : 0;
3227 invalidateHwcGeometry();
3228 repaintEverything();
3229 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003231 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 reply->writeInt32(0);
3233 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003234 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003235 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 return NO_ERROR;
3237 case 1013: {
3238 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003239 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3240 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003241 return NO_ERROR;
3242 }
3243 case 1014: {
3244 // daltonize
3245 n = data.readInt32();
3246 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003247 case 1:
3248 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3249 break;
3250 case 2:
3251 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3252 break;
3253 case 3:
3254 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3255 break;
3256 default:
3257 mDaltonizer.setType(ColorBlindnessType::None);
3258 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003259 }
3260 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003261 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003262 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003263 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003264 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003265 invalidateHwcGeometry();
3266 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003267 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003269 case 1015: {
3270 // apply a color matrix
3271 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003272 if (n) {
3273 // color matrix is sent as mat3 matrix followed by vec3
3274 // offset, then packed into a mat4 where the last row is
3275 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003276 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003277 for (size_t j = 0; j < 4; j++) {
3278 mColorMatrix[i][j] = data.readFloat();
3279 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003280 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003281 } else {
3282 mColorMatrix = mat4();
3283 }
3284 invalidateHwcGeometry();
3285 repaintEverything();
3286 return NO_ERROR;
3287 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003288 // This is an experimental interface
3289 // Needs to be shifted to proper binder interface when we productize
3290 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003291 n = data.readInt32();
3292 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003293 return NO_ERROR;
3294 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003295 case 1017: {
3296 n = data.readInt32();
3297 mForceFullDamage = static_cast<bool>(n);
3298 return NO_ERROR;
3299 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003300 case 1018: { // Modify Choreographer's phase offset
3301 n = data.readInt32();
3302 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3303 return NO_ERROR;
3304 }
3305 case 1019: { // Modify SurfaceFlinger's phase offset
3306 n = data.readInt32();
3307 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3308 return NO_ERROR;
3309 }
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07003310 case 1021: { // Disable HWC virtual displays
3311 n = data.readInt32();
3312 mUseHwcVirtualDisplays = !n;
3313 return NO_ERROR;
3314 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 }
3316 }
3317 return err;
3318}
3319
Mathias Agopian53331da2011-08-22 21:44:41 -07003320void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003321 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003322 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003323}
3324
Mathias Agopian59119e62010-10-11 12:37:43 -07003325// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003326// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003327// ---------------------------------------------------------------------------
3328
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003329/* The code below is here to handle b/8734824
3330 *
3331 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003332 * from the surfaceflinger thread to the calling binder thread, where they
3333 * are executed. This allows the calling thread in the calling process to be
3334 * reused and not depend on having "enough" binder threads to handle the
3335 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003336 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003337class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003338 /* Parts of GraphicProducerWrapper are run on two different threads,
3339 * communicating by sending messages via Looper but also by shared member
3340 * data. Coherence maintenance is subtle and in places implicit (ugh).
3341 *
3342 * Don't rely on Looper's sendMessage/handleMessage providing
3343 * release/acquire semantics for any data not actually in the Message.
3344 * Data going from surfaceflinger to binder threads needs to be
3345 * synchronized explicitly.
3346 *
3347 * Barrier open/wait do provide release/acquire semantics. This provides
3348 * implicit synchronization for data coming back from binder to
3349 * surfaceflinger threads.
3350 */
3351
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003352 sp<IGraphicBufferProducer> impl;
3353 sp<Looper> looper;
3354 status_t result;
3355 bool exitPending;
3356 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003357 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003358 uint32_t code;
3359 Parcel const* data;
3360 Parcel* reply;
3361
3362 enum {
3363 MSG_API_CALL,
3364 MSG_EXIT
3365 };
3366
3367 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003368 * Called on surfaceflinger thread. This is called by our "fake"
3369 * BpGraphicBufferProducer. We package the data and reply Parcel and
3370 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003371 */
3372 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003373 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003374 this->code = code;
3375 this->data = &data;
3376 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003377 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003378 // if we've exited, we run the message synchronously right here.
3379 // note (JH): as far as I can tell from looking at the code, this
3380 // never actually happens. if it does, i'm not sure if it happens
3381 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003382 handleMessage(Message(MSG_API_CALL));
3383 } else {
3384 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003385 // Prevent stores to this->{code, data, reply} from being
3386 // reordered later than the construction of Message.
3387 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003388 looper->sendMessage(this, Message(MSG_API_CALL));
3389 barrier.wait();
3390 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003391 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003392 }
3393
3394 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003395 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003396 * call the real BpGraphicBufferProducer.
3397 */
3398 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003399 int what = message.what;
3400 // Prevent reads below from happening before the read from Message
3401 atomic_thread_fence(memory_order_acquire);
3402 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003403 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003404 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003405 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003406 exitRequested = true;
3407 }
3408 }
3409
3410public:
Jesse Hallb154c422014-07-13 12:47:02 -07003411 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3412 : impl(impl),
3413 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003414 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003415 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003416 exitRequested(false),
3417 code(0),
3418 data(NULL),
3419 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003420 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003421
Jesse Hallb154c422014-07-13 12:47:02 -07003422 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003423 status_t waitForResponse() {
3424 do {
3425 looper->pollOnce(-1);
3426 } while (!exitRequested);
3427 return result;
3428 }
3429
Jesse Hallb154c422014-07-13 12:47:02 -07003430 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003431 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003432 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003433 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003434 // Ensure this->result is visible to the binder thread before it
3435 // handles the message.
3436 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003437 looper->sendMessage(this, Message(MSG_EXIT));
3438 }
3439};
3440
3441
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003442status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3443 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003444 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003445 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003446 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003447
3448 if (CC_UNLIKELY(display == 0))
3449 return BAD_VALUE;
3450
3451 if (CC_UNLIKELY(producer == 0))
3452 return BAD_VALUE;
3453
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003454 // if we have secure windows on this display, never allow the screen capture
3455 // unless the producer interface is local (i.e.: we can take a screenshot for
3456 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003457 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003458
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003459 // Convert to surfaceflinger's internal rotation type.
3460 Transform::orientation_flags rotationFlags;
3461 switch (rotation) {
3462 case ISurfaceComposer::eRotateNone:
3463 rotationFlags = Transform::ROT_0;
3464 break;
3465 case ISurfaceComposer::eRotate90:
3466 rotationFlags = Transform::ROT_90;
3467 break;
3468 case ISurfaceComposer::eRotate180:
3469 rotationFlags = Transform::ROT_180;
3470 break;
3471 case ISurfaceComposer::eRotate270:
3472 rotationFlags = Transform::ROT_270;
3473 break;
3474 default:
3475 rotationFlags = Transform::ROT_0;
3476 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3477 break;
3478 }
3479
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003480 class MessageCaptureScreen : public MessageBase {
3481 SurfaceFlinger* flinger;
3482 sp<IBinder> display;
3483 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003484 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003485 uint32_t reqWidth, reqHeight;
3486 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003487 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003488 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003489 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003490 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003491 public:
3492 MessageCaptureScreen(SurfaceFlinger* flinger,
3493 const sp<IBinder>& display,
3494 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003495 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003496 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003497 bool useIdentityTransform,
3498 Transform::orientation_flags rotation,
3499 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003500 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003501 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003502 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003503 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003504 rotation(rotation), result(PERMISSION_DENIED),
3505 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003506 {
3507 }
3508 status_t getResult() const {
3509 return result;
3510 }
3511 virtual bool handler() {
3512 Mutex::Autolock _l(flinger->mStateLock);
3513 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003514 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003515 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003516 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003517 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003518 return true;
3519 }
3520 };
3521
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003522 // this creates a "fake" BBinder which will serve as a "fake" remote
3523 // binder to receive the marshaled calls and forward them to the
3524 // real remote (a BpGraphicBufferProducer)
3525 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3526
3527 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3528 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003529 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003530 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003531 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003532 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533
3534 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003535 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003536 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003537 }
3538 return res;
3539}
3540
Mathias Agopian180f10d2013-04-10 22:55:41 -07003541
3542void SurfaceFlinger::renderScreenImplLocked(
3543 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003544 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003545 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003546 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003547{
3548 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003549 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003550
3551 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003552 const int32_t hw_w = hw->getWidth();
3553 const int32_t hw_h = hw->getHeight();
3554 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003555 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003556
Dan Stozac1879002014-05-22 15:59:05 -07003557 // if a default or invalid sourceCrop is passed in, set reasonable values
3558 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3559 !sourceCrop.isValid()) {
3560 sourceCrop.setLeftTop(Point(0, 0));
3561 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3562 }
3563
3564 // ensure that sourceCrop is inside screen
3565 if (sourceCrop.left < 0) {
3566 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3567 }
Dan Stozabe31f442014-06-11 11:20:54 -07003568 if (sourceCrop.right > hw_w) {
3569 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003570 }
3571 if (sourceCrop.top < 0) {
3572 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3573 }
Dan Stozabe31f442014-06-11 11:20:54 -07003574 if (sourceCrop.bottom > hw_h) {
3575 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003576 }
3577
Mathias Agopian180f10d2013-04-10 22:55:41 -07003578 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003579 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003580
3581 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003582 engine.setViewportAndProjection(
3583 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003584 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003585
3586 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003587 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003588
3589 const LayerVector& layers( mDrawingState.layersSortedByZ );
3590 const size_t count = layers.size();
3591 for (size_t i=0 ; i<count ; ++i) {
3592 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003593 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003594 if (state.layerStack == hw->getLayerStack()) {
3595 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3596 if (layer->isVisible()) {
3597 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003598 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003599 if (filtering) layer->setFiltering(false);
3600 }
3601 }
3602 }
3603 }
3604
Mathias Agopian931bda12013-08-28 18:11:46 -07003605 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003606}
3607
3608
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003609status_t SurfaceFlinger::captureScreenImplLocked(
3610 const sp<const DisplayDevice>& hw,
3611 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003612 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003613 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003614 bool useIdentityTransform, Transform::orientation_flags rotation,
3615 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003616{
3617 ATRACE_CALL();
3618
Mathias Agopian180f10d2013-04-10 22:55:41 -07003619 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003620 uint32_t hw_w = hw->getWidth();
3621 uint32_t hw_h = hw->getHeight();
3622
3623 if (rotation & Transform::ROT_90) {
3624 std::swap(hw_w, hw_h);
3625 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003626
Mathias Agopian180f10d2013-04-10 22:55:41 -07003627 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3628 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3629 reqWidth, reqHeight, hw_w, hw_h);
3630 return BAD_VALUE;
3631 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003632
Mathias Agopian180f10d2013-04-10 22:55:41 -07003633 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3634 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3635
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003636 bool secureLayerIsVisible = false;
3637 const LayerVector& layers(mDrawingState.layersSortedByZ);
3638 const size_t count = layers.size();
3639 for (size_t i = 0 ; i < count ; ++i) {
3640 const sp<Layer>& layer(layers[i]);
3641 const Layer::State& state(layer->getDrawingState());
3642 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3643 state.z <= maxLayerZ && layer->isVisible() &&
3644 layer->isSecure()) {
3645 secureLayerIsVisible = true;
3646 }
3647 }
3648
3649 if (!isLocalScreenshot && secureLayerIsVisible) {
3650 ALOGW("FB is protected: PERMISSION_DENIED");
3651 return PERMISSION_DENIED;
3652 }
3653
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003654 // create a surface (because we're a producer, and we need to
3655 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003656 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003657
3658 // Put the screenshot Surface into async mode so that
3659 // Layer::headFenceHasSignaled will always return true and we'll latch the
3660 // first buffer regardless of whether or not its acquire fence has
3661 // signaled. This is needed to avoid a race condition in the rotation
3662 // animation. See b/30209608
3663 sur->setAsyncMode(true);
3664
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003665 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003666
Michael Lentine5a16a622015-05-21 13:48:24 -07003667 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3668 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003669 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3670 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003671
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003672 int err = 0;
3673 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003674 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003675 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3676 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003677
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003678 if (err == NO_ERROR) {
3679 ANativeWindowBuffer* buffer;
3680 /* TODO: Once we have the sync framework everywhere this can use
3681 * server-side waits on the fence that dequeueBuffer returns.
3682 */
3683 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3684 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003685 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003686 // create an EGLImage from the buffer so we can later
3687 // turn it into a texture
3688 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3689 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3690 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003691 // this binds the given EGLImage as a framebuffer for the
3692 // duration of this scope.
3693 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3694 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003695 // this will in fact render into our dequeued buffer
3696 // via an FBO, which means we didn't have to create
3697 // an EGLSurface and therefore we're not
3698 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003699 renderScreenImplLocked(
3700 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3701 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003702
Riley Andrews86639902014-08-15 12:27:24 -07003703 // Attempt to create a sync khr object that can produce a sync point. If that
3704 // isn't available, create a non-dupable sync object in the fallback path and
3705 // wait on it directly.
3706 EGLSyncKHR sync;
3707 if (!DEBUG_SCREENSHOTS) {
3708 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003709 // native fence fd will not be populated until flush() is done.
3710 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003711 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003712 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003713 }
Riley Andrews86639902014-08-15 12:27:24 -07003714 if (sync != EGL_NO_SYNC_KHR) {
3715 // get the sync fd
3716 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3717 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3718 ALOGW("captureScreen: failed to dup sync khr object");
3719 syncFd = -1;
3720 }
3721 eglDestroySyncKHR(mEGLDisplay, sync);
3722 } else {
3723 // fallback path
3724 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3725 if (sync != EGL_NO_SYNC_KHR) {
3726 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3727 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3728 EGLint eglErr = eglGetError();
3729 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3730 ALOGW("captureScreen: fence wait timed out");
3731 } else {
3732 ALOGW_IF(eglErr != EGL_SUCCESS,
3733 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3734 }
3735 eglDestroySyncKHR(mEGLDisplay, sync);
3736 } else {
3737 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3738 }
3739 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003740 if (DEBUG_SCREENSHOTS) {
3741 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3742 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3743 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3744 hw, minLayerZ, maxLayerZ);
3745 delete [] pixels;
3746 }
3747
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003748 } else {
3749 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3750 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003751 window->cancelBuffer(window, buffer, syncFd);
3752 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003753 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003754 // destroy our image
3755 eglDestroyImageKHR(mEGLDisplay, image);
3756 } else {
3757 result = BAD_VALUE;
3758 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003759 if (buffer) {
3760 // queueBuffer takes ownership of syncFd
3761 result = window->queueBuffer(window, buffer, syncFd);
3762 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003763 }
3764 } else {
3765 result = BAD_VALUE;
3766 }
3767 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3768 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003769
Mathias Agopian74c40c02010-09-29 13:02:36 -07003770 return result;
3771}
3772
Mathias Agopiand5556842013-09-19 17:08:37 -07003773void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3774 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003775 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003776 for (size_t y=0 ; y<h ; y++) {
3777 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3778 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003779 if (p[x] != 0xFF000000) return;
3780 }
3781 }
3782 ALOGE("*** we just took a black screenshot ***\n"
3783 "requested minz=%d, maxz=%d, layerStack=%d",
3784 minLayerZ, maxLayerZ, hw->getLayerStack());
3785 const LayerVector& layers( mDrawingState.layersSortedByZ );
3786 const size_t count = layers.size();
3787 for (size_t i=0 ; i<count ; ++i) {
3788 const sp<Layer>& layer(layers[i]);
3789 const Layer::State& state(layer->getDrawingState());
3790 const bool visible = (state.layerStack == hw->getLayerStack())
3791 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3792 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003793 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003794 visible ? '+' : '-',
3795 i, layer->getName().string(), state.layerStack, state.z,
3796 layer->isVisible(), state.flags, state.alpha);
3797 }
3798 }
3799}
3800
Pablo Ceballosce796e72016-02-04 19:10:51 -08003801bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3802 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3803 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3804}
3805
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003806// ---------------------------------------------------------------------------
3807
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003808SurfaceFlinger::LayerVector::LayerVector() {
3809}
3810
3811SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003812 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003813}
3814
3815int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3816 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003817{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003818 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003819 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3820 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003821
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003822 uint32_t ls = l->getCurrentState().layerStack;
3823 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003824 if (ls != rs)
3825 return ls - rs;
3826
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003827 uint32_t lz = l->getCurrentState().z;
3828 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003829 if (lz != rz)
3830 return lz - rz;
3831
3832 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003833}
3834
3835// ---------------------------------------------------------------------------
3836
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003837SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003838 : type(DisplayDevice::DISPLAY_ID_INVALID),
3839 layerStack(DisplayDevice::NO_LAYER_STACK),
3840 orientation(0),
3841 width(0),
3842 height(0),
3843 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003844}
3845
Pablo Ceballos53390e12015-08-04 11:25:59 -07003846SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3847 DisplayDevice::DisplayType type, bool isSecure)
3848 : type(type),
3849 layerStack(DisplayDevice::NO_LAYER_STACK),
3850 orientation(0),
3851 width(0),
3852 height(0),
3853 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003854 viewport.makeInvalid();
3855 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003856}
3857
3858// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003860}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003861
3862
3863#if defined(__gl_h_)
3864#error "don't include gl/gl.h in this file"
3865#endif
3866
3867#if defined(__gl2_h_)
3868#error "don't include gl2/gl2.h in this file"
3869#endif