blob: ea9fe214b45bc04258b1b87db4abbdfb775e35db [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700152 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700153 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700154 mDaltonize(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
Dan Stoza14cd37c2015-07-09 12:43:33 -0700169 property_get("debug.sf.drop_missed_frames", value, "0");
170 mDropMissedFrames = atoi(value);
171
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800172 property_get("debug.sf.showupdates", value, "0");
173 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700174
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700175 property_get("debug.sf.ddms", value, "0");
176 mDebugDDMS = atoi(value);
177 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700178 if (!startDdmConnection()) {
179 // start failed, and DDMS debugging not enabled
180 mDebugDDMS = 0;
181 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700182 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700183 ALOGI_IF(mDebugRegion, "showupdates enabled");
184 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800185}
186
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800187void SurfaceFlinger::onFirstRef()
188{
189 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800190}
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192SurfaceFlinger::~SurfaceFlinger()
193{
Mathias Agopiana4912602012-07-12 14:25:33 -0700194 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
195 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
196 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197}
198
Dan Stozac7014012014-02-14 15:03:43 -0800199void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800200{
201 // the window manager died on us. prepare its eulogy.
202
Andy McFadden13a082e2012-08-24 10:16:42 -0700203 // restore initial conditions (default device unblank, etc)
204 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205
206 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700207 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800208}
209
Mathias Agopian7e27f052010-05-28 14:22:23 -0700210sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211{
Mathias Agopian96f08192010-06-02 23:28:45 -0700212 sp<ISurfaceComposerClient> bclient;
213 sp<Client> client(new Client(this));
214 status_t err = client->initCheck();
215 if (err == NO_ERROR) {
216 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218 return bclient;
219}
220
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700221sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
222 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700223{
224 class DisplayToken : public BBinder {
225 sp<SurfaceFlinger> flinger;
226 virtual ~DisplayToken() {
227 // no more references, this display must be terminated
228 Mutex::Autolock _l(flinger->mStateLock);
229 flinger->mCurrentState.displays.removeItem(this);
230 flinger->setTransactionFlags(eDisplayTransactionNeeded);
231 }
232 public:
233 DisplayToken(const sp<SurfaceFlinger>& flinger)
234 : flinger(flinger) {
235 }
236 };
237
238 sp<BBinder> token = new DisplayToken(this);
239
240 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700241 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700242 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700243 mCurrentState.displays.add(token, info);
244
245 return token;
246}
247
Jesse Hall6c913be2013-08-08 12:15:49 -0700248void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
249 Mutex::Autolock _l(mStateLock);
250
251 ssize_t idx = mCurrentState.displays.indexOfKey(display);
252 if (idx < 0) {
253 ALOGW("destroyDisplay: invalid display token");
254 return;
255 }
256
257 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
258 if (!info.isVirtualDisplay()) {
259 ALOGE("destroyDisplay called for non-virtual display");
260 return;
261 }
262
263 mCurrentState.displays.removeItemsAt(idx);
264 setTransactionFlags(eDisplayTransactionNeeded);
265}
266
Jesse Hall692c7232012-11-08 15:41:56 -0800267void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800268 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800269 ALOGW_IF(mBuiltinDisplays[type],
270 "Overwriting display token for display type %d", type);
271 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800272 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700273 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800274 mCurrentState.displays.add(mBuiltinDisplays[type], info);
275}
276
Mathias Agopiane57f2922012-08-09 16:29:12 -0700277sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700278 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
280 return NULL;
281 }
Jesse Hall692c7232012-11-08 15:41:56 -0800282 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700283}
284
Jamie Gennis9a78c902011-01-12 18:30:40 -0800285sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
286{
287 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
288 return gba;
289}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700290
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291void SurfaceFlinger::bootFinished()
292{
293 const nsecs_t now = systemTime();
294 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000295 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700296 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700297
298 // wait patiently for the window manager death
299 const String16 name("window");
300 sp<IBinder> window(defaultServiceManager()->getService(name));
301 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700302 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700303 }
304
305 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700306 // formerly we would just kill the process, but we now ask it to exit so it
307 // can choose where to stop the animation.
308 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700309
310 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
311 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
312 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313}
314
Mathias Agopian3f844832013-08-07 21:24:32 -0700315void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700316 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700317 RenderEngine& engine;
318 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700319 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700320 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
321 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700322 }
323 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700324 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700325 return true;
326 }
327 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700328 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700329}
330
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700331class DispSyncSource : public VSyncSource, private DispSync::Callback {
332public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700333 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
334 const char* label) :
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700335 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700336 mTraceVsync(traceVsync),
Andy McFadden5167ec62014-05-22 13:08:43 -0700337 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
338 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700339 mDispSync(dispSync),
340 mCallbackMutex(),
341 mCallback(),
342 mVsyncMutex(),
343 mPhaseOffset(phaseOffset),
344 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700345
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700346 virtual ~DispSyncSource() {}
347
348 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700349 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700350 if (enable) {
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700351 status_t err = mDispSync->addEventListener(mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352 static_cast<DispSync::Callback*>(this));
353 if (err != NO_ERROR) {
354 ALOGE("error registering vsync callback: %s (%d)",
355 strerror(-err), err);
356 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700357 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700358 } else {
359 status_t err = mDispSync->removeEventListener(
360 static_cast<DispSync::Callback*>(this));
361 if (err != NO_ERROR) {
362 ALOGE("error unregistering vsync callback: %s (%d)",
363 strerror(-err), err);
364 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700365 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700366 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700367 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 }
369
370 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700371 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700372 mCallback = callback;
373 }
374
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700375 virtual void setPhaseOffset(nsecs_t phaseOffset) {
376 Mutex::Autolock lock(mVsyncMutex);
377
378 // Normalize phaseOffset to [0, period)
379 auto period = mDispSync->getPeriod();
380 phaseOffset %= period;
381 if (phaseOffset < 0) {
382 // If we're here, then phaseOffset is in (-period, 0). After this
383 // operation, it will be in (0, period)
384 phaseOffset += period;
385 }
386 mPhaseOffset = phaseOffset;
387
388 // If we're not enabled, we don't need to mess with the listeners
389 if (!mEnabled) {
390 return;
391 }
392
393 // Remove the listener with the old offset
394 status_t err = mDispSync->removeEventListener(
395 static_cast<DispSync::Callback*>(this));
396 if (err != NO_ERROR) {
397 ALOGE("error unregistering vsync callback: %s (%d)",
398 strerror(-err), err);
399 }
400
401 // Add a listener with the new offset
402 err = mDispSync->addEventListener(mPhaseOffset,
403 static_cast<DispSync::Callback*>(this));
404 if (err != NO_ERROR) {
405 ALOGE("error registering vsync callback: %s (%d)",
406 strerror(-err), err);
407 }
408 }
409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410private:
411 virtual void onDispSyncEvent(nsecs_t when) {
412 sp<VSyncSource::Callback> callback;
413 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700414 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 callback = mCallback;
416
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700417 if (mTraceVsync) {
418 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700419 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700420 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 }
422
423 if (callback != NULL) {
424 callback->onVSyncEvent(when);
425 }
426 }
427
428 int mValue;
429
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700430 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 const String8 mVsyncOnLabel;
432 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435
436 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438
439 Mutex mVsyncMutex; // Protects the following
440 nsecs_t mPhaseOffset;
441 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442};
443
444void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700445 ALOGI( "SurfaceFlinger's main thread ready to run. "
446 "Initializing graphics H/W...");
447
Dan Stoza9e56aa02015-11-02 13:00:03 -0800448 { // Autolock scope
449 Mutex::Autolock _l(mStateLock);
450
451 // initialize EGL for the default display
452 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
453 eglInitialize(mEGLDisplay, NULL, NULL);
454
455 // start the EventThread
456 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
457 vsyncPhaseOffsetNs, true, "app");
458 mEventThread = new EventThread(vsyncSrc);
459 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
460 sfVsyncPhaseOffsetNs, true, "sf");
461 mSFEventThread = new EventThread(sfVsyncSrc);
462 mEventQueue.setEventThread(mSFEventThread);
463
464 // Get a RenderEngine for the given display / config (can't fail)
465 mRenderEngine = RenderEngine::create(mEGLDisplay,
466 HAL_PIXEL_FORMAT_RGBA_8888);
467 }
468
469 // Drop the state lock while we initialize the hardware composer. We drop
470 // the lock because on creation, it will call back into SurfaceFlinger to
471 // initialize the primary display.
472 mHwc = new HWComposer(this);
473 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
474
Jesse Hall692c7232012-11-08 15:41:56 -0800475 Mutex::Autolock _l(mStateLock);
476
Mathias Agopian875d8e12013-06-07 15:35:48 -0700477 // retrieve the EGL context that was selected/created
478 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700479
Mathias Agopianda27af92012-09-13 18:17:13 -0700480 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
481 "couldn't create EGLContext");
482
Dan Stoza9e56aa02015-11-02 13:00:03 -0800483 // make the GLContext current so that we can create textures when creating
484 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700485 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
486
Jamie Gennisd1700752013-10-14 12:22:52 -0700487 mEventControlThread = new EventControlThread(this);
488 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
489
Mathias Agopian92a979a2012-08-02 18:32:23 -0700490 // initialize our drawing state
491 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700492
Andy McFadden13a082e2012-08-24 10:16:42 -0700493 // set initial conditions (e.g. unblank default device)
494 initializeDisplays();
495
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700496 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700497 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498
Dan Stoza9e56aa02015-11-02 13:00:03 -0800499 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700500}
501
Mathias Agopiana67e4182012-06-19 17:26:12 -0700502void SurfaceFlinger::startBootAnim() {
503 // start boot animation
504 property_set("service.bootanim.exit", "0");
505 property_set("ctl.start", "bootanim");
506}
507
Mathias Agopian875d8e12013-06-07 15:35:48 -0700508size_t SurfaceFlinger::getMaxTextureSize() const {
509 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700510}
511
Mathias Agopian875d8e12013-06-07 15:35:48 -0700512size_t SurfaceFlinger::getMaxViewportDims() const {
513 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700514}
515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800516// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800517
Jamie Gennis582270d2011-08-17 18:19:00 -0700518bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800519 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800520 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800521 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700522 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800523}
524
Dan Stoza7f7da322014-05-02 15:26:25 -0700525status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
526 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700527 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700528 return BAD_VALUE;
529 }
530
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500531 if (!display.get())
532 return NAME_NOT_FOUND;
533
Jesse Hall692c7232012-11-08 15:41:56 -0800534 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700535 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800536 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700537 type = i;
538 break;
539 }
540 }
541
542 if (type < 0) {
543 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700544 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700545
Mathias Agopian8b736f12012-08-13 17:54:26 -0700546 // TODO: Not sure if display density should handled by SF any longer
547 class Density {
548 static int getDensityFromProperty(char const* propName) {
549 char property[PROPERTY_VALUE_MAX];
550 int density = 0;
551 if (property_get(propName, property, NULL) > 0) {
552 density = atoi(property);
553 }
554 return density;
555 }
556 public:
557 static int getEmuDensity() {
558 return getDensityFromProperty("qemu.sf.lcd_density"); }
559 static int getBuildDensity() {
560 return getDensityFromProperty("ro.sf.lcd_density"); }
561 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700562
Dan Stoza7f7da322014-05-02 15:26:25 -0700563 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700566 DisplayInfo info = DisplayInfo();
567
Dan Stoza9e56aa02015-11-02 13:00:03 -0800568 float xdpi = hwConfig->getDpiX();
569 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700570
571 if (type == DisplayDevice::DISPLAY_PRIMARY) {
572 // The density of the device is provided by a build property
573 float density = Density::getBuildDensity() / 160.0f;
574 if (density == 0) {
575 // the build doesn't provide a density -- this is wrong!
576 // use xdpi instead
577 ALOGE("ro.sf.lcd_density must be defined as a build property");
578 density = xdpi / 160.0f;
579 }
580 if (Density::getEmuDensity()) {
581 // if "qemu.sf.lcd_density" is specified, it overrides everything
582 xdpi = ydpi = density = Density::getEmuDensity();
583 density /= 160.0f;
584 }
585 info.density = density;
586
587 // TODO: this needs to go away (currently needed only by webkit)
588 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
589 info.orientation = hw->getOrientation();
590 } else {
591 // TODO: where should this value come from?
592 static const int TV_DENSITY = 213;
593 info.density = TV_DENSITY / 160.0f;
594 info.orientation = 0;
595 }
596
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597 info.w = hwConfig->getWidth();
598 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700599 info.xdpi = xdpi;
600 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700602 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603
604 // TODO: Hook this back up
605 info.colorTransform = 0;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700606
607 // This is how far in advance a buffer must be queued for
608 // presentation at a given time. If you want a buffer to appear
609 // on the screen at time N, you must submit the buffer before
610 // (N - presentationDeadline).
611 //
612 // Normally it's one full refresh period (to give SF a chance to
613 // latch the buffer), but this can be reduced by configuring a
614 // DispSync offset. Any additional delays introduced by the hardware
615 // composer or panel must be accounted for here.
616 //
617 // We add an additional 1ms to allow for processing time and
618 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619 info.presentationDeadline = hwConfig->getVsyncPeriod() -
620 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700621
622 // All non-virtual displays are currently considered secure.
623 info.secure = true;
624
625 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700626 }
627
Dan Stoza7f7da322014-05-02 15:26:25 -0700628 return NO_ERROR;
629}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700630
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800631status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700632 DisplayStatInfo* stats) {
633 if (stats == NULL) {
634 return BAD_VALUE;
635 }
636
637 // FIXME for now we always return stats for the primary display
638 memset(stats, 0, sizeof(*stats));
639 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
640 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
641 return NO_ERROR;
642}
643
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700644int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700645 sp<DisplayDevice> device(getDisplayDevice(display));
646 if (device != NULL) {
647 return device->getActiveConfig();
648 }
649 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700650}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700651
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700652void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
653 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
654 this);
655 int32_t type = hw->getDisplayType();
656 int currentMode = hw->getActiveConfig();
657
658 if (mode == currentMode) {
659 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
660 return;
661 }
662
663 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
664 ALOGW("Trying to set config for virtual display");
665 return;
666 }
667
668 hw->setActiveConfig(mode);
669 getHwComposer().setActiveConfig(type, mode);
670}
671
672status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
673 class MessageSetActiveConfig: public MessageBase {
674 SurfaceFlinger& mFlinger;
675 sp<IBinder> mDisplay;
676 int mMode;
677 public:
678 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
679 int mode) :
680 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
681 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700682 Vector<DisplayInfo> configs;
683 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700684 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700685 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700686 mMode, configs.size());
687 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700688 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
689 if (hw == NULL) {
690 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700691 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700692 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
693 ALOGW("Attempt to set active config = %d for virtual display",
694 mMode);
695 } else {
696 mFlinger.setActiveConfigInternal(hw, mMode);
697 }
698 return true;
699 }
700 };
701 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
702 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700703 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700704}
705
Svetoslavd85084b2014-03-20 10:28:31 -0700706status_t SurfaceFlinger::clearAnimationFrameStats() {
707 Mutex::Autolock _l(mStateLock);
708 mAnimFrameTracker.clearStats();
709 return NO_ERROR;
710}
711
712status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
713 Mutex::Autolock _l(mStateLock);
714 mAnimFrameTracker.getStats(outStats);
715 return NO_ERROR;
716}
717
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800718// ----------------------------------------------------------------------------
719
720sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800721 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700722}
723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800725
726void SurfaceFlinger::waitForEvent() {
727 mEventQueue.waitMessage();
728}
729
730void SurfaceFlinger::signalTransaction() {
731 mEventQueue.invalidate();
732}
733
734void SurfaceFlinger::signalLayerUpdate() {
735 mEventQueue.invalidate();
736}
737
738void SurfaceFlinger::signalRefresh() {
739 mEventQueue.refresh();
740}
741
742status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800743 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800744 return mEventQueue.postMessage(msg, reltime);
745}
746
747status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800748 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800749 status_t res = mEventQueue.postMessage(msg, reltime);
750 if (res == NO_ERROR) {
751 msg->wait();
752 }
753 return res;
754}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800755
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700756void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700757 do {
758 waitForEvent();
759 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800760}
761
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700762void SurfaceFlinger::enableHardwareVsync() {
763 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700764 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700765 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700766 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
767 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700768 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700769 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700770}
771
Jesse Hall948fe0c2013-10-14 12:56:09 -0700772void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700773 Mutex::Autolock _l(mHWVsyncLock);
774
Jesse Hall948fe0c2013-10-14 12:56:09 -0700775 if (makeAvailable) {
776 mHWVsyncAvailable = true;
777 } else if (!mHWVsyncAvailable) {
778 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
779 return;
780 }
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
783 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700784
785 mPrimaryDispSync.reset();
786 mPrimaryDispSync.setPeriod(period);
787
788 if (!mPrimaryHWVsyncEnabled) {
789 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700790 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
791 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700792 mPrimaryHWVsyncEnabled = true;
793 }
794}
795
Jesse Hall948fe0c2013-10-14 12:56:09 -0700796void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700797 Mutex::Autolock _l(mHWVsyncLock);
798 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700799 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
800 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700801 mPrimaryDispSync.endResync();
802 mPrimaryHWVsyncEnabled = false;
803 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700804 if (makeUnavailable) {
805 mHWVsyncAvailable = false;
806 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700807}
808
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700810 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700811
Jamie Gennisd1700752013-10-14 12:22:52 -0700812 { // Scope for the lock
813 Mutex::Autolock _l(mHWVsyncLock);
814 if (type == 0 && mPrimaryHWVsyncEnabled) {
815 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700816 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700817 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700818
819 if (needsHwVsync) {
820 enableHardwareVsync();
821 } else {
822 disableHardwareVsync(false);
823 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700824}
825
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
827 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
828 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
829 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700830
Dan Stoza9e56aa02015-11-02 13:00:03 -0800831 // All non-virtual displays are currently considered secure.
832 bool isSecure = true;
833
834 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
835 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
836 wp<IBinder> token = mBuiltinDisplays[type];
837
838 sp<IGraphicBufferProducer> producer;
839 sp<IGraphicBufferConsumer> consumer;
840 BufferQueue::createBufferQueue(&producer, &consumer,
841 new GraphicBufferAlloc());
842
843 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
844 DisplayDevice::DISPLAY_PRIMARY, consumer);
845 sp<DisplayDevice> hw = new DisplayDevice(this,
846 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
847 producer, mRenderEngine->getEGLConfig());
848 mDisplays.add(token, hw);
849 } else {
850 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700851 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800852 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800853 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700854 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800855 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
856 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700857 }
858 setTransactionFlags(eDisplayTransactionNeeded);
859
Andy McFadden9e9689c2012-10-10 18:17:51 -0700860 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700861 }
Mathias Agopian86303202012-07-24 22:46:10 -0700862}
863
Dan Stoza9e56aa02015-11-02 13:00:03 -0800864void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700865 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800866 getHwComposer().setVsyncEnabled(disp,
867 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700868}
869
Mathias Agopian4fec8732012-06-29 14:12:52 -0700870void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800871 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800872 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800873 case MessageQueue::TRANSACTION: {
874 handleMessageTransaction();
875 break;
876 }
877 case MessageQueue::INVALIDATE: {
878 bool refreshNeeded = handleMessageTransaction();
879 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800880 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800881 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800882 // Signal a refresh if a transaction modified the window state,
883 // a new buffer was latched, or if HWC has requested a full
884 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800885 signalRefresh();
886 }
887 break;
888 }
889 case MessageQueue::REFRESH: {
890 handleMessageRefresh();
891 break;
892 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800893 }
894}
895
Dan Stoza6b9454d2014-11-07 16:00:59 -0800896bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700897 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700898 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700899 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800900 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700901 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800902 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700903}
904
Dan Stoza6b9454d2014-11-07 16:00:59 -0800905bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700906 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800907 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700908}
909
910void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700911 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700912
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700913#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -0800914 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700915#else
916 nsecs_t refreshStartTime = 0;
917#endif
Dan Stoza14cd37c2015-07-09 12:43:33 -0700918 static nsecs_t previousExpectedPresent = 0;
919 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
920 static bool previousFrameMissed = false;
921 bool frameMissed = (expectedPresent == previousExpectedPresent);
922 if (frameMissed != previousFrameMissed) {
923 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
924 }
925 previousFrameMissed = frameMissed;
926
927 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
928 // Latch buffers, but don't send anything to HWC, then signal another
929 // wakeup for the next vsync
930 preComposition();
931 repaintEverything();
932 } else {
933 preComposition();
934 rebuildLayerStacks();
935 setUpHWComposer();
936 doDebugFlashRegions();
937 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800938 postComposition(refreshStartTime);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700939 }
940
Dan Stoza9e56aa02015-11-02 13:00:03 -0800941 // Release any buffers which were replaced this frame
942 for (auto& layer : mLayersWithQueuedFrames) {
943 layer->releasePendingBuffer();
944 }
945 mLayersWithQueuedFrames.clear();
946
Dan Stoza14cd37c2015-07-09 12:43:33 -0700947 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700948}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700949
Mathias Agopiancd60f992012-08-16 16:28:27 -0700950void SurfaceFlinger::doDebugFlashRegions()
951{
952 // is debugging enabled
953 if (CC_LIKELY(!mDebugRegion))
954 return;
955
956 const bool repaintEverything = mRepaintEverything;
957 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
958 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700959 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700960 // transform the dirty region into this screen's coordinate space
961 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
962 if (!dirtyRegion.isEmpty()) {
963 // redraw the whole screen
964 doComposeSurfaces(hw, Region(hw->bounds()));
965
966 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700967 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -0700968 RenderEngine& engine(getRenderEngine());
969 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
970
Mathias Agopianda27af92012-09-13 18:17:13 -0700971 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -0700972 }
973 }
974 }
975
976 postFramebuffer();
977
978 if (mDebugRegion > 1) {
979 usleep(mDebugRegion * 1000);
980 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -0700981
Dan Stoza9e56aa02015-11-02 13:00:03 -0800982 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
983 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
984 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
985 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -0700986 }
Mathias Agopiancd60f992012-08-16 16:28:27 -0700987}
988
989void SurfaceFlinger::preComposition()
990{
Dan Stoza9e56aa02015-11-02 13:00:03 -0800991 ATRACE_CALL();
992 ALOGV("preComposition");
993
Mathias Agopiancd60f992012-08-16 16:28:27 -0700994 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700995 const LayerVector& layers(mDrawingState.layersSortedByZ);
996 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700997 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700998 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700999 needExtraInvalidate = true;
1000 }
1001 }
1002 if (needExtraInvalidate) {
1003 signalLayerUpdate();
1004 }
1005}
1006
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001007#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001008void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001009#else
1010void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1011#endif
Mathias Agopiancd60f992012-08-16 16:28:27 -07001012{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001013 ATRACE_CALL();
1014 ALOGV("postComposition");
1015
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001016 const LayerVector& layers(mDrawingState.layersSortedByZ);
1017 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001018 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001019 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001020 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001021
Dan Stoza9e56aa02015-11-02 13:00:03 -08001022 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001023
1024 if (presentFence->isValid()) {
1025 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1026 enableHardwareVsync();
1027 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001028 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029 }
1030 }
1031
Dan Stozab90cf072015-03-05 11:05:59 -08001032 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001033 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001034 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001035 enableHardwareVsync();
1036 }
1037 }
1038
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001039#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001040 mFenceTracker.addFrame(refreshStartTime, presentFence,
1041 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001042#endif
Pablo Ceballos40845df2016-01-25 17:41:15 -08001043
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001044 if (mAnimCompositionPending) {
1045 mAnimCompositionPending = false;
1046
Jesse Halla9a1b002013-02-27 16:39:25 -08001047 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001048 mAnimFrameTracker.setActualPresentFence(presentFence);
1049 } else {
1050 // The HWC doesn't support present fences, so use the refresh
1051 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001052 nsecs_t presentTime =
1053 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001054 mAnimFrameTracker.setActualPresentTime(presentTime);
1055 }
1056 mAnimFrameTracker.advanceFrame();
1057 }
Dan Stozab90cf072015-03-05 11:05:59 -08001058
1059 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1060 return;
1061 }
1062
1063 nsecs_t currentTime = systemTime();
1064 if (mHasPoweredOff) {
1065 mHasPoweredOff = false;
1066 } else {
1067 nsecs_t period = mPrimaryDispSync.getPeriod();
1068 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1069 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1070 if (numPeriods < NUM_BUCKETS - 1) {
1071 mFrameBuckets[numPeriods] += elapsedTime;
1072 } else {
1073 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1074 }
1075 mTotalTime += elapsedTime;
1076 }
1077 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001078}
1079
1080void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001081 ATRACE_CALL();
1082 ALOGV("rebuildLayerStacks");
1083
Mathias Agopiancd60f992012-08-16 16:28:27 -07001084 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001085 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001086 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001087 mVisibleRegionsDirty = false;
1088 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001089
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001090 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001091 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001092 Region opaqueRegion;
1093 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001094 Vector<sp<Layer>> layersSortedByZ;
1095 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1096 const Transform& tr(displayDevice->getTransform());
1097 const Rect bounds(displayDevice->getBounds());
1098 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001099 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001100 displayDevice->getLayerStack(), dirtyRegion,
1101 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001102
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001103 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001104 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001105 const sp<Layer>& layer(layers[i]);
1106 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001107 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001108 Region drawRegion(tr.transform(
1109 layer->visibleNonTransparentRegion));
1110 drawRegion.andSelf(bounds);
1111 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001112 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001113 } else {
1114 // Clear out the HWC layer if this layer was
1115 // previously visible, but no longer is
1116 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1117 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001118 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001119 }
1120 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001121 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001122 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1123 displayDevice->undefinedRegion.set(bounds);
1124 displayDevice->undefinedRegion.subtractSelf(
1125 tr.transform(opaqueRegion));
1126 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001127 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001128 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001129}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001130
Mathias Agopiancd60f992012-08-16 16:28:27 -07001131void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 ATRACE_CALL();
1133 ALOGV("setUpHWComposer");
1134
Jesse Hall028dc8f2013-08-20 16:35:32 -07001135 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001136 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1137 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1138 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1139
1140 // If nothing has changed (!dirty), don't recompose.
1141 // If something changed, but we don't currently have any visible layers,
1142 // and didn't when we last did a composition, then skip it this time.
1143 // The second rule does two things:
1144 // - When all layers are removed from a display, we'll emit one black
1145 // frame, then nothing more until we get new layers.
1146 // - When a display is created with a private layer stack, we won't
1147 // emit any black frames until a layer is added to the layer stack.
1148 bool mustRecompose = dirty && !(empty && wasEmpty);
1149
1150 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1151 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1152 mustRecompose ? "doing" : "skipping",
1153 dirty ? "+" : "-",
1154 empty ? "+" : "-",
1155 wasEmpty ? "+" : "-");
1156
Dan Stoza71433162014-02-04 16:22:36 -08001157 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001158
1159 if (mustRecompose) {
1160 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1161 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001162 }
1163
Dan Stoza9e56aa02015-11-02 13:00:03 -08001164 // build the h/w work list
1165 if (CC_UNLIKELY(mGeometryInvalid)) {
1166 mGeometryInvalid = false;
1167 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1168 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1169 const auto hwcId = displayDevice->getHwcDisplayId();
1170 if (hwcId >= 0) {
1171 const Vector<sp<Layer>>& currentLayers(
1172 displayDevice->getVisibleLayersSortedByZ());
1173 bool foundLayerWithoutHwc = false;
1174 for (auto& layer : currentLayers) {
1175 if (!layer->hasHwcLayer(hwcId)) {
1176 auto hwcLayer = mHwc->createLayer(hwcId);
1177 if (hwcLayer) {
1178 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1179 } else {
1180 layer->forceClientComposition(hwcId);
1181 foundLayerWithoutHwc = true;
1182 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001183 }
1184 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001185
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 layer->setGeometry(displayDevice);
1187 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1188 mHasColorMatrix) {
1189 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001190 }
1191 }
1192 }
1193 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001194 }
Riley Andrews03414a12014-07-01 14:22:59 -07001195
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 // Set the per-frame data
1197 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1198 auto& displayDevice = mDisplays[displayId];
1199 const auto hwcId = displayDevice->getHwcDisplayId();
1200 if (hwcId < 0) {
1201 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001202 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1204 layer->setPerFrameData(displayDevice);
1205 }
1206 }
1207
1208 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1209 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1210 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1211 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001212 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001213}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001214
Mathias Agopiancd60f992012-08-16 16:28:27 -07001215void SurfaceFlinger::doComposition() {
1216 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217 ALOGV("doComposition");
1218
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001219 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001220 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001221 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001222 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001223 // transform the dirty region into this screen's coordinate space
1224 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001225
1226 // repaint the framebuffer (if needed)
1227 doDisplayComposition(hw, dirtyRegion);
1228
Mathias Agopiancd60f992012-08-16 16:28:27 -07001229 hw->dirtyRegion.clear();
1230 hw->flip(hw->swapRegion);
1231 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001232 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001233 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001234 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001235}
1236
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001237void SurfaceFlinger::postFramebuffer()
1238{
Mathias Agopian841cde52012-03-01 15:44:37 -08001239 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001240 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001241
Mathias Agopiana44b0412011-10-16 18:46:35 -07001242 const nsecs_t now = systemTime();
1243 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001244
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1246 auto& displayDevice = mDisplays[displayId];
1247 const auto hwcId = displayDevice->getHwcDisplayId();
1248 if (hwcId >= 0) {
1249 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001250 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001251 if (displayId == 0) {
1252 // Make the default display current because the VirtualDisplayDevice
1253 // code cannot deal with dequeueBuffer() being called outside of the
1254 // composition loop; however the code below can call glFlush() which
1255 // is allowed to (and does in some case) call dequeueBuffer().
1256 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1257 }
1258 displayDevice->onSwapBuffersCompleted();
1259 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1260 sp<Fence> releaseFence = Fence::NO_FENCE;
1261 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1262 releaseFence = displayDevice->getClientTargetAcquireFence();
1263 } else {
1264 auto hwcLayer = layer->getHwcLayer(hwcId);
1265 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001266 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001267 layer->onLayerDisplayed(releaseFence);
1268 }
1269 if (hwcId >= 0) {
1270 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001271 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001272 }
1273
Mathias Agopiana44b0412011-10-16 18:46:35 -07001274 mLastSwapBufferTime = systemTime() - now;
1275 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001276
1277 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1278 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1279 logFrameStats();
1280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281}
1282
Mathias Agopian87baae12012-07-31 12:38:26 -07001283void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001284{
Mathias Agopian841cde52012-03-01 15:44:37 -08001285 ATRACE_CALL();
1286
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001287 // here we keep a copy of the drawing state (that is the state that's
1288 // going to be overwritten by handleTransactionLocked()) outside of
1289 // mStateLock so that the side-effects of the State assignment
1290 // don't happen with mStateLock held (which can cause deadlocks).
1291 State drawingState(mDrawingState);
1292
Mathias Agopianca4d3602011-05-19 15:38:14 -07001293 Mutex::Autolock _l(mStateLock);
1294 const nsecs_t now = systemTime();
1295 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001296
Mathias Agopianca4d3602011-05-19 15:38:14 -07001297 // Here we're guaranteed that some transaction flags are set
1298 // so we can call handleTransactionLocked() unconditionally.
1299 // We call getTransactionFlags(), which will also clear the flags,
1300 // with mStateLock held to guarantee that mCurrentState won't change
1301 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001302
Mathias Agopiane57f2922012-08-09 16:29:12 -07001303 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001304 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001305
Mathias Agopianca4d3602011-05-19 15:38:14 -07001306 mLastTransactionTime = systemTime() - now;
1307 mDebugInTransaction = 0;
1308 invalidateHwcGeometry();
1309 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001310}
1311
Mathias Agopian87baae12012-07-31 12:38:26 -07001312void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001313{
1314 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001315 const size_t count = currentLayers.size();
1316
Dan Stoza7dde5992015-05-22 09:51:44 -07001317 // Notify all layers of available frames
1318 for (size_t i = 0; i < count; ++i) {
1319 currentLayers[i]->notifyAvailableFrames();
1320 }
1321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001322 /*
1323 * Traversal of the children
1324 * (perform the transaction for each of them if needed)
1325 */
1326
Mathias Agopian3559b072012-08-15 13:46:03 -07001327 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001329 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001330 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1331 if (!trFlags) continue;
1332
1333 const uint32_t flags = layer->doTransaction(0);
1334 if (flags & Layer::eVisibleRegion)
1335 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336 }
1337 }
1338
1339 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001340 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341 */
1342
Mathias Agopiane57f2922012-08-09 16:29:12 -07001343 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001344 // here we take advantage of Vector's copy-on-write semantics to
1345 // improve performance by skipping the transaction entirely when
1346 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001347 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1348 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001349 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001351 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001352 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001353
1354 // find the displays that were removed
1355 // (ie: in drawing state but not in current state)
1356 // also handle displays that changed
1357 // (ie: displays that are in both lists)
1358 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001359 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1360 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001361 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001362 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001363 // Call makeCurrent() on the primary display so we can
1364 // be sure that nothing associated with this display
1365 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001366 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001367 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001368 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1369 if (hw != NULL)
1370 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001371 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001372 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001373 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001374 } else {
1375 ALOGW("trying to remove the main display");
1376 }
1377 } else {
1378 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001379 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001380 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001381 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1382 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001383 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001384 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001385 // recreating the DisplayDevice, so we just remove it
1386 // from the drawing state, so that it get re-added
1387 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001388 sp<DisplayDevice> hw(getDisplayDevice(display));
1389 if (hw != NULL)
1390 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001391 mDisplays.removeItem(display);
1392 mDrawingState.displays.removeItemsAt(i);
1393 dc--; i--;
1394 // at this point we must loop to the next item
1395 continue;
1396 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001397
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001398 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001399 if (disp != NULL) {
1400 if (state.layerStack != draw[i].layerStack) {
1401 disp->setLayerStack(state.layerStack);
1402 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001403 if ((state.orientation != draw[i].orientation)
1404 || (state.viewport != draw[i].viewport)
1405 || (state.frame != draw[i].frame))
1406 {
1407 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001408 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001409 }
Michael Lentine47e45402014-07-18 15:34:25 -07001410 if (state.width != draw[i].width || state.height != draw[i].height) {
1411 disp->setDisplaySize(state.width, state.height);
1412 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001413 }
1414 }
1415 }
1416
1417 // find displays that were added
1418 // (ie: in current state but not in drawing state)
1419 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001420 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001421 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001422
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001423 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001424 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001425 sp<IGraphicBufferProducer> bqProducer;
1426 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001427 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1428 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001429
Dan Stoza9e56aa02015-11-02 13:00:03 -08001430 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001431 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001432 // Virtual displays without a surface are dormant:
1433 // they have external state (layer stack, projection,
1434 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001435 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001436
Dan Stoza1f3efb12014-10-15 16:34:55 -07001437 int width = 0;
1438 int status = state.surface->query(
1439 NATIVE_WINDOW_WIDTH, &width);
1440 ALOGE_IF(status != NO_ERROR,
1441 "Unable to query width (%d)", status);
1442 int height = 0;
1443 status = state.surface->query(
1444 NATIVE_WINDOW_HEIGHT, &height);
1445 ALOGE_IF(status != NO_ERROR,
1446 "Unable to query height (%d)", status);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001447
Dan Stoza9e56aa02015-11-02 13:00:03 -08001448 mHwc->allocateVirtualDisplay(width, height,
1449 &hwcId);
1450
1451 sp<VirtualDisplaySurface> vds =
1452 new VirtualDisplaySurface(*mHwc,
1453 hwcId, state.surface, bqProducer,
1454 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001455
1456 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001457 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001458 }
1459 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001460 ALOGE_IF(state.surface!=NULL,
1461 "adding a supported display, but rendering "
1462 "surface is provided (%p), ignoring it",
1463 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001464 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1465 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1466 dispSurface = new FramebufferSurface(*mHwc,
1467 DisplayDevice::DISPLAY_EXTERNAL,
1468 bqConsumer);
1469 producer = bqProducer;
1470 } else {
1471 ALOGE("Attempted to add non-external non-virtual"
1472 " display");
1473 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001474 }
1475
1476 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001477 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001478 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001479 state.type, hwcId, state.isSecure, display,
1480 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001481 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001482 hw->setLayerStack(state.layerStack);
1483 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001484 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001485 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001486 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001487 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001488 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001489 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001490 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001491 }
1492 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001495
Mathias Agopian84300952012-11-21 16:02:13 -08001496 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1497 // The transform hint might have changed for some layers
1498 // (either because a display has changed, or because a layer
1499 // as changed).
1500 //
1501 // Walk through all the layers in currentLayers,
1502 // and update their transform hint.
1503 //
1504 // If a layer is visible only on a single display, then that
1505 // display is used to calculate the hint, otherwise we use the
1506 // default display.
1507 //
1508 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1509 // the hint is set before we acquire a buffer from the surface texture.
1510 //
1511 // NOTE: layer transactions have taken place already, so we use their
1512 // drawing state. However, SurfaceFlinger's own transaction has not
1513 // happened yet, so we must use the current state layer list
1514 // (soon to become the drawing state list).
1515 //
1516 sp<const DisplayDevice> disp;
1517 uint32_t currentlayerStack = 0;
1518 for (size_t i=0; i<count; i++) {
1519 // NOTE: we rely on the fact that layers are sorted by
1520 // layerStack first (so we don't have to traverse the list
1521 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001522 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001523 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001524 if (i==0 || currentlayerStack != layerStack) {
1525 currentlayerStack = layerStack;
1526 // figure out if this layerstack is mirrored
1527 // (more than one display) if so, pick the default display,
1528 // if not, pick the only display it's on.
1529 disp.clear();
1530 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1531 sp<const DisplayDevice> hw(mDisplays[dpy]);
1532 if (hw->getLayerStack() == currentlayerStack) {
1533 if (disp == NULL) {
1534 disp = hw;
1535 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001536 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001537 break;
1538 }
1539 }
1540 }
1541 }
Chet Haase91d25932013-04-11 15:24:55 -07001542 if (disp == NULL) {
1543 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1544 // redraw after transform hint changes. See bug 8508397.
1545
1546 // could be null when this layer is using a layerStack
1547 // that is not visible on any display. Also can occur at
1548 // screen off/on times.
1549 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001550 }
Chet Haase91d25932013-04-11 15:24:55 -07001551 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001552 }
1553 }
1554
1555
Mathias Agopian3559b072012-08-15 13:46:03 -07001556 /*
1557 * Perform our own transaction if needed
1558 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001559
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001560 const LayerVector& layers(mDrawingState.layersSortedByZ);
1561 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001562 // layers have been added
1563 mVisibleRegionsDirty = true;
1564 }
1565
1566 // some layers might have been removed, so
1567 // we need to update the regions they're exposing.
1568 if (mLayersRemoved) {
1569 mLayersRemoved = false;
1570 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001571 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001572 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001573 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001574 if (currentLayers.indexOf(layer) < 0) {
1575 // this layer is not visible anymore
1576 // TODO: we could traverse the tree from front to back and
1577 // compute the actual visible region
1578 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001579 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001580 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001581 Region(Rect(s.active.w, s.active.h)));
1582 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001583 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001584 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001585 }
1586
1587 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001588
1589 updateCursorAsync();
1590}
1591
1592void SurfaceFlinger::updateCursorAsync()
1593{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001594 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1595 auto& displayDevice = mDisplays[displayId];
1596 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001597 continue;
1598 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001599
1600 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1601 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001602 }
1603 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001604}
1605
1606void SurfaceFlinger::commitTransaction()
1607{
1608 if (!mLayersPendingRemoval.isEmpty()) {
1609 // Notify removed layers now that they can't be drawn from
1610 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1611 mLayersPendingRemoval[i]->onRemoved();
1612 }
1613 mLayersPendingRemoval.clear();
1614 }
1615
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001616 // If this transaction is part of a window animation then the next frame
1617 // we composite should be considered an animation as well.
1618 mAnimCompositionPending = mAnimTransactionPending;
1619
Mathias Agopian4fec8732012-06-29 14:12:52 -07001620 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001621 mTransactionPending = false;
1622 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001623 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001624}
1625
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001626void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001627 const LayerVector& currentLayers, uint32_t layerStack,
1628 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001629{
Mathias Agopian841cde52012-03-01 15:44:37 -08001630 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001632
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001633 Region aboveOpaqueLayers;
1634 Region aboveCoveredLayers;
1635 Region dirty;
1636
Mathias Agopian87baae12012-07-31 12:38:26 -07001637 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001638
1639 size_t i = currentLayers.size();
1640 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001641 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001642
1643 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001644 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001645
Jesse Hall01e29052013-02-19 16:13:35 -08001646 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001647 if (s.layerStack != layerStack)
1648 continue;
1649
Mathias Agopianab028732010-03-16 16:41:46 -07001650 /*
1651 * opaqueRegion: area of a surface that is fully opaque.
1652 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001653 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001654
1655 /*
1656 * visibleRegion: area of a surface that is visible on screen
1657 * and not fully transparent. This is essentially the layer's
1658 * footprint minus the opaque regions above it.
1659 * Areas covered by a translucent surface are considered visible.
1660 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001661 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001662
1663 /*
1664 * coveredRegion: area of a surface that is covered by all
1665 * visible regions above it (which includes the translucent areas).
1666 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001667 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001668
Jesse Halla8026d22012-09-25 13:25:04 -07001669 /*
1670 * transparentRegion: area of a surface that is hinted to be completely
1671 * transparent. This is only used to tell when the layer has no visible
1672 * non-transparent regions and can be removed from the layer list. It
1673 * does not affect the visibleRegion of this layer or any layers
1674 * beneath it. The hint may not be correct if apps don't respect the
1675 * SurfaceView restrictions (which, sadly, some don't).
1676 */
1677 Region transparentRegion;
1678
Mathias Agopianab028732010-03-16 16:41:46 -07001679
1680 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001681 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001682 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001683 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001684 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001685 if (!visibleRegion.isEmpty()) {
1686 // Remove the transparent area from the visible region
1687 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001688 const Transform tr(s.active.transform);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001689 if (tr.transformed()) {
1690 if (tr.preserveRects()) {
1691 // transform the transparent region
Mathias Agopian2ca79392013-04-02 18:30:32 -07001692 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001693 } else {
1694 // transformation too complex, can't do the
1695 // transparent region optimization.
Jesse Halla8026d22012-09-25 13:25:04 -07001696 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697 }
1698 } else {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001699 transparentRegion = s.activeTransparentRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700 }
Mathias Agopianab028732010-03-16 16:41:46 -07001701 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001702
Mathias Agopianab028732010-03-16 16:41:46 -07001703 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001704 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001705 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001706 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1707 // the opaque region is the layer's footprint
1708 opaqueRegion = visibleRegion;
1709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001710 }
1711 }
1712
Mathias Agopianab028732010-03-16 16:41:46 -07001713 // Clip the covered region to the visible region
1714 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1715
1716 // Update aboveCoveredLayers for next (lower) layer
1717 aboveCoveredLayers.orSelf(visibleRegion);
1718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001719 // subtract the opaque region covered by the layers above us
1720 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001721
1722 // compute this layer's dirty region
1723 if (layer->contentDirty) {
1724 // we need to invalidate the whole region
1725 dirty = visibleRegion;
1726 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001727 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001728 layer->contentDirty = false;
1729 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001730 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001731 * the exposed region consists of two components:
1732 * 1) what's VISIBLE now and was COVERED before
1733 * 2) what's EXPOSED now less what was EXPOSED before
1734 *
1735 * note that (1) is conservative, we start with the whole
1736 * visible region but only keep what used to be covered by
1737 * something -- which mean it may have been exposed.
1738 *
1739 * (2) handles areas that were not covered by anything but got
1740 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001741 */
Mathias Agopianab028732010-03-16 16:41:46 -07001742 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001743 const Region oldVisibleRegion = layer->visibleRegion;
1744 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001745 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1746 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001747 }
1748 dirty.subtractSelf(aboveOpaqueLayers);
1749
1750 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001751 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001752
Mathias Agopianab028732010-03-16 16:41:46 -07001753 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001754 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001755
Jesse Halla8026d22012-09-25 13:25:04 -07001756 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001757 layer->setVisibleRegion(visibleRegion);
1758 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001759 layer->setVisibleNonTransparentRegion(
1760 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001761 }
1762
Mathias Agopian87baae12012-07-31 12:38:26 -07001763 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001764}
1765
Mathias Agopian87baae12012-07-31 12:38:26 -07001766void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1767 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001768 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001769 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1770 if (hw->getLayerStack() == layerStack) {
1771 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001772 }
1773 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001774}
1775
Dan Stoza6b9454d2014-11-07 16:00:59 -08001776bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001778 ALOGV("handlePageFlip");
1779
Mathias Agopian4fec8732012-06-29 14:12:52 -07001780 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781
Mathias Agopian4fec8732012-06-29 14:12:52 -07001782 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001783 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001784 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001785
1786 // Store the set of layers that need updates. This set must not change as
1787 // buffers are being latched, as this could result in a deadlock.
1788 // Example: Two producers share the same command stream and:
1789 // 1.) Layer 0 is latched
1790 // 2.) Layer 0 gets a new frame
1791 // 2.) Layer 1 gets a new frame
1792 // 3.) Layer 1 is latched.
1793 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1794 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001795 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001796 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001797 if (layer->hasQueuedFrame()) {
1798 frameQueued = true;
1799 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001800 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001801 } else {
1802 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001803 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001804 } else {
1805 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001806 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001807 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001809 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001810 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001811 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001812 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001813 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001814
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001815 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816
1817 // If we will need to wake up at some time in the future to deal with a
1818 // queued frame that shouldn't be displayed during this vsync period, wake
1819 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001821 signalLayerUpdate();
1822 }
1823
1824 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001826}
1827
Mathias Agopianad456f92011-01-13 17:53:01 -08001828void SurfaceFlinger::invalidateHwcGeometry()
1829{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001831}
1832
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001833
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001835 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001836{
Dan Stoza71433162014-02-04 16:22:36 -08001837 // We only need to actually compose the display if:
1838 // 1) It is being handled by hardware composer, which may need this to
1839 // keep its virtual display state machine in sync, or
1840 // 2) There is work to be done (the dirty region isn't empty)
1841 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1842 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001844 return;
1845 }
1846
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 ALOGV("doDisplayComposition");
1848
Mathias Agopian87baae12012-07-31 12:38:26 -07001849 Region dirtyRegion(inDirtyRegion);
1850
Mathias Agopianb8a55602009-06-26 19:06:36 -07001851 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001852 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853
Mathias Agopian42977342012-08-05 00:40:46 -07001854 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001855 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001856 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1857 // takes a rectangle, we must make sure to update that whole
1858 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001859 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001860 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001861 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001862 // We need to redraw the rectangle that will be updated
1863 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001864 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001865 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001866 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001867 } else {
1868 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001869 dirtyRegion.set(hw->bounds());
1870 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001871 }
1872 }
1873
Alan Viverette9c5a3332013-09-12 20:04:35 -07001874 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001875 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001876 } else {
1877 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001878 mat4 colorMatrix = mColorMatrix;
1879 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001880 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001881 }
Dan Stozaf0087992014-10-20 15:46:09 -07001882 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001883 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001884 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001887 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001888 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001889
1890 // swap buffers (presentation)
1891 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001892}
1893
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894bool SurfaceFlinger::doComposeSurfaces(
1895 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001896{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001898
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 const auto hwcId = displayDevice->getHwcDisplayId();
1900 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1901 if (hasClientComposition) {
1902 ALOGV("hasClientComposition");
1903
1904 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001905 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001907 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1908 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1909 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1910 }
1911 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001912 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001913
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001914 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1916 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001917 // when using overlays, we assume a fully transparent framebuffer
1918 // NOTE: we could reduce how much we need to clear, for instance
1919 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001920 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001921 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001922 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001923 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001924 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001926
1927 // we remove the scissor part
1928 // we're left with the letterbox region
1929 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001931
1932 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001934
1935 // but limit it to the dirty region
1936 region.andSelf(dirty);
1937
Mathias Agopianb9494d52012-04-18 02:28:45 -07001938 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001939 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001940 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001942 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001943 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001944
Dan Stoza9e56aa02015-11-02 13:00:03 -08001945 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07001946 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001947 // scissor on the main display. It should never be needed
1948 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 const Rect& bounds(displayDevice->getBounds());
1950 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001951 if (scissor != bounds) {
1952 // scissor doesn't match the screen's dimensions, so we
1953 // need to clear everything outside of it and enable
1954 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001955
Mathias Agopianf45c5102012-10-24 16:29:17 -07001956 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 const uint32_t height = displayDevice->getHeight();
1958 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07001959 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001960 }
1961 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001962 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001963
Mathias Agopian85d751c2012-08-29 16:59:24 -07001964 /*
1965 * and then, render the layers targeted at the framebuffer
1966 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001967
Dan Stoza9e56aa02015-11-02 13:00:03 -08001968 ALOGV("Rendering client layers");
1969 const Transform& displayTransform = displayDevice->getTransform();
1970 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07001971 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08001972 bool firstLayer = true;
1973 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1974 const Region clip(dirty.intersect(
1975 displayTransform.transform(layer->visibleRegion)));
1976 ALOGV("Layer: %s", layer->getName().string());
1977 ALOGV(" Composition type: %s",
1978 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07001979 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 switch (layer->getCompositionType(hwcId)) {
1981 case HWC2::Composition::Cursor:
1982 case HWC2::Composition::Device:
1983 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07001984 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
1986 layer->isOpaque(state) && (state.alpha == 1.0f)
1987 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988 // never clear the very first layer since we're
1989 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001992 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 case HWC2::Composition::Client: {
1995 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07001996 break;
1997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07001999 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 } else {
2002 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002003 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002005 }
2006 } else {
2007 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002009 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002011 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002013 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002014 }
2015 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002016
2017 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002019 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020}
2021
Mathias Agopian3f844832013-08-07 21:24:32 -07002022void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002023 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002024 RenderEngine& engine(getRenderEngine());
2025 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002026}
2027
Dan Stoza7d89d062015-04-30 13:29:25 -07002028status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002029 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002030 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002031 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002032{
Dan Stoza7d89d062015-04-30 13:29:25 -07002033 // add this layer to the current state list
2034 {
2035 Mutex::Autolock _l(mStateLock);
2036 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2037 return NO_MEMORY;
2038 }
2039 mCurrentState.layersSortedByZ.add(lbc);
2040 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2041 }
2042
Mathias Agopian96f08192010-06-02 23:28:45 -07002043 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002044 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002045
Dan Stoza7d89d062015-04-30 13:29:25 -07002046 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002047}
2048
Mathias Agopian3f844832013-08-07 21:24:32 -07002049status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002051 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002053 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002054 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002055 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002056 return NO_ERROR;
2057 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002058 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059}
2060
Dan Stozac7014012014-02-14 15:03:43 -08002061uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002062 return android_atomic_release_load(&mTransactionFlags);
2063}
2064
Mathias Agopian3f844832013-08-07 21:24:32 -07002065uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002066 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2067}
2068
Mathias Agopian3f844832013-08-07 21:24:32 -07002069uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002070 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2071 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002072 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002073 }
2074 return old;
2075}
2076
Mathias Agopian8b33f032012-07-24 20:43:54 -07002077void SurfaceFlinger::setTransactionState(
2078 const Vector<ComposerState>& state,
2079 const Vector<DisplayState>& displays,
2080 uint32_t flags)
2081{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002082 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002083 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002084 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002085
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002086 if (flags & eAnimation) {
2087 // For window updates that are part of an animation we must wait for
2088 // previous animation "frames" to be handled.
2089 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002090 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002091 if (CC_UNLIKELY(err != NO_ERROR)) {
2092 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002093 // caller after a few seconds.
2094 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2095 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002096 mAnimTransactionPending = false;
2097 break;
2098 }
2099 }
2100 }
2101
Mathias Agopiane57f2922012-08-09 16:29:12 -07002102 size_t count = displays.size();
2103 for (size_t i=0 ; i<count ; i++) {
2104 const DisplayState& s(displays[i]);
2105 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002106 }
2107
Mathias Agopiane57f2922012-08-09 16:29:12 -07002108 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002109 for (size_t i=0 ; i<count ; i++) {
2110 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002111 // Here we need to check that the interface we're given is indeed
2112 // one of our own. A malicious client could give us a NULL
2113 // IInterface, or one of its own or even one of our own but a
2114 // different type. All these situations would cause us to crash.
2115 //
2116 // NOTE: it would be better to use RTTI as we could directly check
2117 // that we have a Client*. however, RTTI is disabled in Android.
2118 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002119 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002120 if (binder != NULL) {
2121 String16 desc(binder->getInterfaceDescriptor());
2122 if (desc == ISurfaceComposerClient::descriptor) {
2123 sp<Client> client( static_cast<Client *>(s.client.get()) );
2124 transactionFlags |= setClientStateLocked(client, s.state);
2125 }
2126 }
2127 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002128 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002129
Mathias Agopian386aa982011-11-07 21:58:03 -08002130 if (transactionFlags) {
2131 // this triggers the transaction
2132 setTransactionFlags(transactionFlags);
2133
2134 // if this is a synchronous transaction, wait for it to take effect
2135 // before returning.
2136 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002137 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002138 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002139 if (flags & eAnimation) {
2140 mAnimTransactionPending = true;
2141 }
2142 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002143 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2144 if (CC_UNLIKELY(err != NO_ERROR)) {
2145 // just in case something goes wrong in SF, return to the
2146 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002147 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2148 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002149 break;
2150 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002151 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002152 }
2153}
2154
Mathias Agopiane57f2922012-08-09 16:29:12 -07002155uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2156{
Jesse Hall9a143922012-10-04 16:29:19 -07002157 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2158 if (dpyIdx < 0)
2159 return 0;
2160
Mathias Agopiane57f2922012-08-09 16:29:12 -07002161 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002162 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002163 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002164 const uint32_t what = s.what;
2165 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002166 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167 disp.surface = s.surface;
2168 flags |= eDisplayTransactionNeeded;
2169 }
2170 }
2171 if (what & DisplayState::eLayerStackChanged) {
2172 if (disp.layerStack != s.layerStack) {
2173 disp.layerStack = s.layerStack;
2174 flags |= eDisplayTransactionNeeded;
2175 }
2176 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002177 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002178 if (disp.orientation != s.orientation) {
2179 disp.orientation = s.orientation;
2180 flags |= eDisplayTransactionNeeded;
2181 }
2182 if (disp.frame != s.frame) {
2183 disp.frame = s.frame;
2184 flags |= eDisplayTransactionNeeded;
2185 }
2186 if (disp.viewport != s.viewport) {
2187 disp.viewport = s.viewport;
2188 flags |= eDisplayTransactionNeeded;
2189 }
2190 }
Michael Lentine47e45402014-07-18 15:34:25 -07002191 if (what & DisplayState::eDisplaySizeChanged) {
2192 if (disp.width != s.width) {
2193 disp.width = s.width;
2194 flags |= eDisplayTransactionNeeded;
2195 }
2196 if (disp.height != s.height) {
2197 disp.height = s.height;
2198 flags |= eDisplayTransactionNeeded;
2199 }
2200 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002201 }
2202 return flags;
2203}
2204
2205uint32_t SurfaceFlinger::setClientStateLocked(
2206 const sp<Client>& client,
2207 const layer_state_t& s)
2208{
2209 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002210 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002211 if (layer != 0) {
2212 const uint32_t what = s.what;
2213 if (what & layer_state_t::ePositionChanged) {
2214 if (layer->setPosition(s.x, s.y))
2215 flags |= eTraversalNeeded;
2216 }
2217 if (what & layer_state_t::eLayerChanged) {
2218 // NOTE: index needs to be calculated before we update the state
2219 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002220 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002221 mCurrentState.layersSortedByZ.removeAt(idx);
2222 mCurrentState.layersSortedByZ.add(layer);
2223 // we need traversal (state changed)
2224 // AND transaction (list changed)
2225 flags |= eTransactionNeeded|eTraversalNeeded;
2226 }
2227 }
2228 if (what & layer_state_t::eSizeChanged) {
2229 if (layer->setSize(s.w, s.h)) {
2230 flags |= eTraversalNeeded;
2231 }
2232 }
2233 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002235 flags |= eTraversalNeeded;
2236 }
2237 if (what & layer_state_t::eMatrixChanged) {
2238 if (layer->setMatrix(s.matrix))
2239 flags |= eTraversalNeeded;
2240 }
2241 if (what & layer_state_t::eTransparentRegionChanged) {
2242 if (layer->setTransparentRegionHint(s.transparentRegion))
2243 flags |= eTraversalNeeded;
2244 }
Dan Stoza23116082015-06-18 14:58:39 -07002245 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002246 if (layer->setFlags(s.flags, s.mask))
2247 flags |= eTraversalNeeded;
2248 }
2249 if (what & layer_state_t::eCropChanged) {
2250 if (layer->setCrop(s.crop))
2251 flags |= eTraversalNeeded;
2252 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002253 if (what & layer_state_t::eFinalCropChanged) {
2254 if (layer->setFinalCrop(s.finalCrop))
2255 flags |= eTraversalNeeded;
2256 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002257 if (what & layer_state_t::eLayerStackChanged) {
2258 // NOTE: index needs to be calculated before we update the state
2259 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002260 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002261 mCurrentState.layersSortedByZ.removeAt(idx);
2262 mCurrentState.layersSortedByZ.add(layer);
2263 // we need traversal (state changed)
2264 // AND transaction (list changed)
2265 flags |= eTransactionNeeded|eTraversalNeeded;
2266 }
2267 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002268 if (what & layer_state_t::eDeferTransaction) {
2269 layer->deferTransactionUntil(s.handle, s.frameNumber);
2270 // We don't trigger a traversal here because if no other state is
2271 // changed, we don't want this to cause any more work
2272 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002273 }
2274 return flags;
2275}
2276
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002277status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002278 const String8& name,
2279 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002280 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2281 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002283 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002284 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002285 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002286 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002287 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002288 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002289
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002290 status_t result = NO_ERROR;
2291
2292 sp<Layer> layer;
2293
Mathias Agopian3165cc22012-08-08 19:42:09 -07002294 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2295 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002296 result = createNormalLayer(client,
2297 name, w, h, flags, format,
2298 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002299 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002300 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002301 result = createDimLayer(client,
2302 name, w, h, flags,
2303 handle, gbp, &layer);
2304 break;
2305 default:
2306 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 break;
2308 }
2309
Dan Stoza7d89d062015-04-30 13:29:25 -07002310 if (result != NO_ERROR) {
2311 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002313
2314 result = addClientLayer(client, *handle, *gbp, layer);
2315 if (result != NO_ERROR) {
2316 return result;
2317 }
2318
2319 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002320 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321}
2322
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002323status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2324 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2325 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326{
2327 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002328 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002329 case PIXEL_FORMAT_TRANSPARENT:
2330 case PIXEL_FORMAT_TRANSLUCENT:
2331 format = PIXEL_FORMAT_RGBA_8888;
2332 break;
2333 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002334 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 break;
2336 }
2337
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002338 *outLayer = new Layer(this, client, name, w, h, flags);
2339 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2340 if (err == NO_ERROR) {
2341 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002342 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002344
2345 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2346 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347}
2348
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002349status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2350 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2351 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002353 *outLayer = new LayerDim(this, client, name, w, h, flags);
2354 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002355 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002356 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002357}
2358
Mathias Agopianac9fa422013-02-11 16:40:36 -08002359status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360{
Mathias Agopian67106042013-03-14 19:18:13 -07002361 // called by the window manager when it wants to remove a Layer
2362 status_t err = NO_ERROR;
2363 sp<Layer> l(client->getLayerUser(handle));
2364 if (l != NULL) {
2365 err = removeLayer(l);
2366 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2367 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002368 }
2369 return err;
2370}
2371
Mathias Agopian13127d82013-03-05 17:47:11 -08002372status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002373{
Mathias Agopian67106042013-03-14 19:18:13 -07002374 // called by ~LayerCleaner() when all references to the IBinder (handle)
2375 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002376 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002377 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002378 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002379 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002380 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002381 "error removing layer=%p (%s)", l.get(), strerror(-err));
2382 }
2383 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384}
2385
Mathias Agopianb60314a2012-04-10 22:09:54 -07002386// ---------------------------------------------------------------------------
2387
Andy McFadden13a082e2012-08-24 10:16:42 -07002388void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002389 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002390 Vector<ComposerState> state;
2391 Vector<DisplayState> displays;
2392 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002393 d.what = DisplayState::eDisplayProjectionChanged |
2394 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002395 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002396 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002397 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002398 d.frame.makeInvalid();
2399 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002400 d.width = 0;
2401 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002402 displays.add(d);
2403 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002404 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002405
Dan Stoza9e56aa02015-11-02 13:00:03 -08002406 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2407 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002408 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002409}
2410
2411void SurfaceFlinger::initializeDisplays() {
2412 class MessageScreenInitialized : public MessageBase {
2413 SurfaceFlinger* flinger;
2414 public:
2415 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2416 virtual bool handler() {
2417 flinger->onInitializeDisplays();
2418 return true;
2419 }
2420 };
2421 sp<MessageBase> msg = new MessageScreenInitialized(this);
2422 postMessageAsync(msg); // we may be called from main thread, use async message
2423}
2424
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002425void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2426 int mode) {
2427 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2428 this);
2429 int32_t type = hw->getDisplayType();
2430 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002431
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002432 if (mode == currentMode) {
2433 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002434 return;
2435 }
2436
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002437 hw->setPowerMode(mode);
2438 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2439 ALOGW("Trying to set power mode for virtual display");
2440 return;
2441 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002443 if (currentMode == HWC_POWER_MODE_OFF) {
2444 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002445 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2446 // FIXME: eventthread only knows about the main display right now
2447 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002448 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002449 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002451 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002452 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002453 repaintEverything();
2454 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002455 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002456 disableHardwareVsync(true); // also cancels any in-progress resync
2457
Mathias Agopiancde87a32012-09-13 14:09:01 -07002458 // FIXME: eventthread only knows about the main display right now
2459 mEventThread->onScreenReleased();
2460 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002461
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002462 getHwComposer().setPowerMode(type, mode);
2463 mVisibleRegionsDirty = true;
2464 // from this point on, SF will stop drawing on this display
2465 } else {
2466 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002467 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002468}
2469
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002470void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2471 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002472 SurfaceFlinger& mFlinger;
2473 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002474 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002475 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002476 MessageSetPowerMode(SurfaceFlinger& flinger,
2477 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2478 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002479 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002480 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002481 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002482 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002483 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002484 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002485 ALOGW("Attempt to set power mode = %d for virtual display",
2486 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002487 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002488 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002489 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002490 return true;
2491 }
2492 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002493 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002494 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002495}
2496
2497// ---------------------------------------------------------------------------
2498
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2500{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002502
Mathias Agopianbd115332013-04-18 16:41:04 -07002503 IPCThreadState* ipc = IPCThreadState::self();
2504 const int pid = ipc->getCallingPid();
2505 const int uid = ipc->getCallingUid();
2506 if ((uid != AID_SHELL) &&
2507 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002508 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002509 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002511 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002512 // (this would indicate SF is stuck, but we want to be able to
2513 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002514 status_t err = mStateLock.timedLock(s2ns(1));
2515 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002516 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002517 result.appendFormat(
2518 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2519 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002520 }
2521
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002522 bool dumpAll = true;
2523 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002524 size_t numArgs = args.size();
2525 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002526 if ((index < numArgs) &&
2527 (args[index] == String16("--list"))) {
2528 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002529 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002530 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002531 }
2532
2533 if ((index < numArgs) &&
2534 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002535 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002536 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002537 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002538 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002539
2540 if ((index < numArgs) &&
2541 (args[index] == String16("--latency-clear"))) {
2542 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002543 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002544 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002545 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002546
2547 if ((index < numArgs) &&
2548 (args[index] == String16("--dispsync"))) {
2549 index++;
2550 mPrimaryDispSync.dump(result);
2551 dumpAll = false;
2552 }
Dan Stozab90cf072015-03-05 11:05:59 -08002553
2554 if ((index < numArgs) &&
2555 (args[index] == String16("--static-screen"))) {
2556 index++;
2557 dumpStaticScreenStats(result);
2558 dumpAll = false;
2559 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002560
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002561#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002562 if ((index < numArgs) &&
2563 (args[index] == String16("--fences"))) {
2564 index++;
2565 mFenceTracker.dump(&result);
2566 dumpAll = false;
2567 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002568#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002570
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002571 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002572 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002573 }
2574
Mathias Agopian9795c422009-08-26 16:36:26 -07002575 if (locked) {
2576 mStateLock.unlock();
2577 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 }
2579 write(fd, result.string(), result.size());
2580 return NO_ERROR;
2581}
2582
Dan Stozac7014012014-02-14 15:03:43 -08002583void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2584 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002585{
2586 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2587 const size_t count = currentLayers.size();
2588 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002589 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002590 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002591 }
2592}
2593
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002594void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002595 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002596{
2597 String8 name;
2598 if (index < args.size()) {
2599 name = String8(args[index]);
2600 index++;
2601 }
2602
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2604 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002605 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002606
2607 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002608 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002609 } else {
2610 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2611 const size_t count = currentLayers.size();
2612 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002613 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002614 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002615 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002616 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002617 }
2618 }
2619}
2620
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002621void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002622 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002623{
2624 String8 name;
2625 if (index < args.size()) {
2626 name = String8(args[index]);
2627 index++;
2628 }
2629
2630 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2631 const size_t count = currentLayers.size();
2632 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002633 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002634 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002635 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002636 }
2637 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002638
Svetoslavd85084b2014-03-20 10:28:31 -07002639 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002640}
2641
Jamie Gennis6547ff42013-07-16 20:12:42 -07002642// This should only be called from the main thread. Otherwise it would need
2643// the lock and should use mCurrentState rather than mDrawingState.
2644void SurfaceFlinger::logFrameStats() {
2645 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2646 const size_t count = drawingLayers.size();
2647 for (size_t i=0 ; i<count ; i++) {
2648 const sp<Layer>& layer(drawingLayers[i]);
2649 layer->logFrameStats();
2650 }
2651
2652 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2653}
2654
Andy McFadden4803b742012-09-24 19:07:20 -07002655/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2656{
2657 static const char* config =
2658 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002659#ifdef HAS_CONTEXT_PRIORITY
2660 " HAS_CONTEXT_PRIORITY"
2661#endif
2662#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2663 " NEVER_DEFAULT_TO_ASYNC_MODE"
2664#endif
2665#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2666 " TARGET_DISABLE_TRIPLE_BUFFERING"
2667#endif
2668 "]";
2669 result.append(config);
2670}
2671
Dan Stozab90cf072015-03-05 11:05:59 -08002672void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2673{
2674 result.appendFormat("Static screen stats:\n");
2675 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2676 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2677 float percent = 100.0f *
2678 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2679 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2680 b + 1, bucketTimeSec, percent);
2681 }
2682 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2683 float percent = 100.0f *
2684 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2685 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2686 NUM_BUCKETS - 1, bucketTimeSec, percent);
2687}
2688
Mathias Agopian74d211a2013-04-22 16:55:35 +02002689void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2690 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002691{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002692 bool colorize = false;
2693 if (index < args.size()
2694 && (args[index] == String16("--color"))) {
2695 colorize = true;
2696 index++;
2697 }
2698
2699 Colorizer colorizer(colorize);
2700
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002701 // figure out if we're stuck somewhere
2702 const nsecs_t now = systemTime();
2703 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2704 const nsecs_t inTransaction(mDebugInTransaction);
2705 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2706 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2707
2708 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002709 * Dump library configuration.
2710 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002711
2712 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002713 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002714 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002715 appendSfConfigString(result);
2716 appendUiConfigString(result);
2717 appendGuiConfigString(result);
2718 result.append("\n");
2719
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002720 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002721 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002722 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002723 result.append(SyncFeatures::getInstance().toString());
2724 result.append("\n");
2725
Dan Stoza9e56aa02015-11-02 13:00:03 -08002726 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2727
Andy McFadden41d67d72014-04-25 16:58:34 -07002728 colorizer.bold(result);
2729 result.append("DispSync configuration: ");
2730 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002731 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2732 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2734 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002735 result.append("\n");
2736
Dan Stozab90cf072015-03-05 11:05:59 -08002737 // Dump static screen stats
2738 result.append("\n");
2739 dumpStaticScreenStats(result);
2740 result.append("\n");
2741
Andy McFadden4803b742012-09-24 19:07:20 -07002742 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002743 * Dump the visible layer list
2744 */
2745 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2746 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002747 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002748 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002749 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002750 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002751 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002752 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002753 }
2754
2755 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002756 * Dump Display state
2757 */
2758
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002759 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002760 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002761 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002762 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2763 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002764 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002765 }
2766
2767 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002768 * Dump SurfaceFlinger global state
2769 */
2770
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002771 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002772 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002773 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002774
Mathias Agopian888c8222012-08-04 21:10:38 -07002775 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002776 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002777
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002778 colorizer.bold(result);
2779 result.appendFormat("EGL implementation : %s\n",
2780 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2781 colorizer.reset(result);
2782 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002783 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002784
Mathias Agopian875d8e12013-06-07 15:35:48 -07002785 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002786
Mathias Agopian42977342012-08-05 00:40:46 -07002787 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002788 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2789 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002790 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002791 " last eglSwapBuffers() time: %f us\n"
2792 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002793 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002794 " refresh-rate : %f fps\n"
2795 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002796 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002797 " gpu_to_cpu_unsupported : %d\n"
2798 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002799 mLastSwapBufferTime/1000.0,
2800 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002801 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002802 1e9 / activeConfig->getVsyncPeriod(),
2803 activeConfig->getDpiX(),
2804 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002805 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002806
Mathias Agopian74d211a2013-04-22 16:55:35 +02002807 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002808 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002809
Mathias Agopian74d211a2013-04-22 16:55:35 +02002810 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002811 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002812
2813 /*
2814 * VSYNC state
2815 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002816 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002817
2818 /*
2819 * Dump HWComposer state
2820 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002821 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002822 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002823 colorizer.reset(result);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002824 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2825 mHasColorMatrix;
2826 result.appendFormat(" h/w composer %s\n",
2827 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002828 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002829
2830 /*
2831 * Dump gralloc state
2832 */
2833 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2834 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002835}
2836
Mathias Agopian13127d82013-03-05 17:47:11 -08002837const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002838SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002839 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002840 wp<IBinder> dpy;
2841 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2842 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2843 dpy = mDisplays.keyAt(i);
2844 break;
2845 }
2846 }
2847 if (dpy == NULL) {
2848 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2849 // Just use the primary display so we have something to return
2850 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2851 }
2852 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002853}
2854
Keun young Park63f165f2012-08-31 10:53:36 -07002855bool SurfaceFlinger::startDdmConnection()
2856{
2857 void* libddmconnection_dso =
2858 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2859 if (!libddmconnection_dso) {
2860 return false;
2861 }
2862 void (*DdmConnection_start)(const char* name);
2863 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002864 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002865 if (!DdmConnection_start) {
2866 dlclose(libddmconnection_dso);
2867 return false;
2868 }
2869 (*DdmConnection_start)(getServiceName());
2870 return true;
2871}
2872
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873status_t SurfaceFlinger::onTransact(
2874 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2875{
2876 switch (code) {
2877 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002878 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002879 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002881 case CLEAR_ANIMATION_FRAME_STATS:
2882 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002883 case SET_POWER_MODE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 {
2885 // codes that require permission check
2886 IPCThreadState* ipc = IPCThreadState::self();
2887 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002888 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002889 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002890 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002891 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002892 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2893 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002895 break;
2896 }
2897 case CAPTURE_SCREEN:
2898 {
2899 // codes that require permission check
2900 IPCThreadState* ipc = IPCThreadState::self();
2901 const int pid = ipc->getCallingPid();
2902 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002903 if ((uid != AID_GRAPHICS) &&
2904 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002905 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002906 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2907 return PERMISSION_DENIED;
2908 }
2909 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910 }
2911 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002912
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002913 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2914 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002915 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002916 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002917 IPCThreadState* ipc = IPCThreadState::self();
2918 const int pid = ipc->getCallingPid();
2919 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002920 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002921 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 return PERMISSION_DENIED;
2923 }
2924 int n;
2925 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07002926 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07002927 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928 return NO_ERROR;
2929 case 1002: // SHOW_UPDATES
2930 n = data.readInt32();
2931 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07002932 invalidateHwcGeometry();
2933 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002934 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07002936 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002937 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002939 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07002940 setTransactionFlags(
2941 eTransactionNeeded|
2942 eDisplayTransactionNeeded|
2943 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002944 return NO_ERROR;
2945 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002946 case 1006:{ // send empty update
2947 signalRefresh();
2948 return NO_ERROR;
2949 }
Mathias Agopian53331da2011-08-22 21:44:41 -07002950 case 1008: // toggle use of hw composer
2951 n = data.readInt32();
2952 mDebugDisableHWC = n ? 1 : 0;
2953 invalidateHwcGeometry();
2954 repaintEverything();
2955 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07002956 case 1009: // toggle use of transform hint
2957 n = data.readInt32();
2958 mDebugDisableTransformHint = n ? 1 : 0;
2959 invalidateHwcGeometry();
2960 repaintEverything();
2961 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07002963 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 reply->writeInt32(0);
2965 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002966 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08002967 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002968 return NO_ERROR;
2969 case 1013: {
2970 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07002971 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2972 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07002973 return NO_ERROR;
2974 }
2975 case 1014: {
2976 // daltonize
2977 n = data.readInt32();
2978 switch (n % 10) {
2979 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2980 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2981 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2982 }
2983 if (n >= 10) {
2984 mDaltonizer.setMode(Daltonizer::correction);
2985 } else {
2986 mDaltonizer.setMode(Daltonizer::simulation);
2987 }
2988 mDaltonize = n > 0;
2989 invalidateHwcGeometry();
2990 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07002991 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07002993 case 1015: {
2994 // apply a color matrix
2995 n = data.readInt32();
2996 mHasColorMatrix = n ? 1 : 0;
2997 if (n) {
2998 // color matrix is sent as mat3 matrix followed by vec3
2999 // offset, then packed into a mat4 where the last row is
3000 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003001 for (size_t i = 0 ; i < 4; i++) {
3002 for (size_t j = 0; j < 4; j++) {
3003 mColorMatrix[i][j] = data.readFloat();
3004 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003005 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003006 } else {
3007 mColorMatrix = mat4();
3008 }
3009 invalidateHwcGeometry();
3010 repaintEverything();
3011 return NO_ERROR;
3012 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003013 // This is an experimental interface
3014 // Needs to be shifted to proper binder interface when we productize
3015 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003016 n = data.readInt32();
3017 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003018 return NO_ERROR;
3019 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003020 case 1017: {
3021 n = data.readInt32();
3022 mForceFullDamage = static_cast<bool>(n);
3023 return NO_ERROR;
3024 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003025 case 1018: { // Modify Choreographer's phase offset
3026 n = data.readInt32();
3027 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3028 return NO_ERROR;
3029 }
3030 case 1019: { // Modify SurfaceFlinger's phase offset
3031 n = data.readInt32();
3032 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3033 return NO_ERROR;
3034 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003035 }
3036 }
3037 return err;
3038}
3039
Mathias Agopian53331da2011-08-22 21:44:41 -07003040void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003041 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003042 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003043}
3044
Mathias Agopian59119e62010-10-11 12:37:43 -07003045// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003046// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003047// ---------------------------------------------------------------------------
3048
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003049/* The code below is here to handle b/8734824
3050 *
3051 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003052 * from the surfaceflinger thread to the calling binder thread, where they
3053 * are executed. This allows the calling thread in the calling process to be
3054 * reused and not depend on having "enough" binder threads to handle the
3055 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003056 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003057class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003058 /* Parts of GraphicProducerWrapper are run on two different threads,
3059 * communicating by sending messages via Looper but also by shared member
3060 * data. Coherence maintenance is subtle and in places implicit (ugh).
3061 *
3062 * Don't rely on Looper's sendMessage/handleMessage providing
3063 * release/acquire semantics for any data not actually in the Message.
3064 * Data going from surfaceflinger to binder threads needs to be
3065 * synchronized explicitly.
3066 *
3067 * Barrier open/wait do provide release/acquire semantics. This provides
3068 * implicit synchronization for data coming back from binder to
3069 * surfaceflinger threads.
3070 */
3071
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003072 sp<IGraphicBufferProducer> impl;
3073 sp<Looper> looper;
3074 status_t result;
3075 bool exitPending;
3076 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003077 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003078 uint32_t code;
3079 Parcel const* data;
3080 Parcel* reply;
3081
3082 enum {
3083 MSG_API_CALL,
3084 MSG_EXIT
3085 };
3086
3087 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003088 * Called on surfaceflinger thread. This is called by our "fake"
3089 * BpGraphicBufferProducer. We package the data and reply Parcel and
3090 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003091 */
3092 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003093 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003094 this->code = code;
3095 this->data = &data;
3096 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003097 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003098 // if we've exited, we run the message synchronously right here.
3099 // note (JH): as far as I can tell from looking at the code, this
3100 // never actually happens. if it does, i'm not sure if it happens
3101 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003102 handleMessage(Message(MSG_API_CALL));
3103 } else {
3104 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003105 // Prevent stores to this->{code, data, reply} from being
3106 // reordered later than the construction of Message.
3107 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003108 looper->sendMessage(this, Message(MSG_API_CALL));
3109 barrier.wait();
3110 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003111 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003112 }
3113
3114 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003115 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003116 * call the real BpGraphicBufferProducer.
3117 */
3118 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003119 int what = message.what;
3120 // Prevent reads below from happening before the read from Message
3121 atomic_thread_fence(memory_order_acquire);
3122 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003123 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003124 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003125 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003126 exitRequested = true;
3127 }
3128 }
3129
3130public:
Jesse Hallb154c422014-07-13 12:47:02 -07003131 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3132 : impl(impl),
3133 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003134 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003135 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003136 exitRequested(false),
3137 code(0),
3138 data(NULL),
3139 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003140 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003141
Jesse Hallb154c422014-07-13 12:47:02 -07003142 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003143 status_t waitForResponse() {
3144 do {
3145 looper->pollOnce(-1);
3146 } while (!exitRequested);
3147 return result;
3148 }
3149
Jesse Hallb154c422014-07-13 12:47:02 -07003150 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003151 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003152 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003153 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003154 // Ensure this->result is visible to the binder thread before it
3155 // handles the message.
3156 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003157 looper->sendMessage(this, Message(MSG_EXIT));
3158 }
3159};
3160
3161
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003162status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3163 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003164 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003165 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003166 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003167
3168 if (CC_UNLIKELY(display == 0))
3169 return BAD_VALUE;
3170
3171 if (CC_UNLIKELY(producer == 0))
3172 return BAD_VALUE;
3173
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003174 // if we have secure windows on this display, never allow the screen capture
3175 // unless the producer interface is local (i.e.: we can take a screenshot for
3176 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003177 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003178
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003179 // Convert to surfaceflinger's internal rotation type.
3180 Transform::orientation_flags rotationFlags;
3181 switch (rotation) {
3182 case ISurfaceComposer::eRotateNone:
3183 rotationFlags = Transform::ROT_0;
3184 break;
3185 case ISurfaceComposer::eRotate90:
3186 rotationFlags = Transform::ROT_90;
3187 break;
3188 case ISurfaceComposer::eRotate180:
3189 rotationFlags = Transform::ROT_180;
3190 break;
3191 case ISurfaceComposer::eRotate270:
3192 rotationFlags = Transform::ROT_270;
3193 break;
3194 default:
3195 rotationFlags = Transform::ROT_0;
3196 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3197 break;
3198 }
3199
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003200 class MessageCaptureScreen : public MessageBase {
3201 SurfaceFlinger* flinger;
3202 sp<IBinder> display;
3203 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003204 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003205 uint32_t reqWidth, reqHeight;
3206 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003207 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003208 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003209 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003210 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003211 public:
3212 MessageCaptureScreen(SurfaceFlinger* flinger,
3213 const sp<IBinder>& display,
3214 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003215 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003216 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003217 bool useIdentityTransform,
3218 Transform::orientation_flags rotation,
3219 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003220 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003221 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003222 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003223 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003224 rotation(rotation), result(PERMISSION_DENIED),
3225 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003226 {
3227 }
3228 status_t getResult() const {
3229 return result;
3230 }
3231 virtual bool handler() {
3232 Mutex::Autolock _l(flinger->mStateLock);
3233 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003234 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003235 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003236 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003237 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003238 return true;
3239 }
3240 };
3241
Mathias Agopian9eb1f052013-04-10 16:27:17 -07003242 // make sure to process transactions before screenshots -- a transaction
3243 // might already be pending but scheduled for VSYNC; this guarantees we
3244 // will handle it before the screenshot. When VSYNC finally arrives
3245 // the scheduled transaction will be a no-op. If no transactions are
3246 // scheduled at this time, this will end-up being a no-op as well.
3247 mEventQueue.invalidateTransactionNow();
3248
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003249 // this creates a "fake" BBinder which will serve as a "fake" remote
3250 // binder to receive the marshaled calls and forward them to the
3251 // real remote (a BpGraphicBufferProducer)
3252 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3253
3254 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3255 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003256 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003257 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003258 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003259 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003260
3261 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003262 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003263 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003264 }
3265 return res;
3266}
3267
Mathias Agopian180f10d2013-04-10 22:55:41 -07003268
3269void SurfaceFlinger::renderScreenImplLocked(
3270 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003271 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003272 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003273 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003274{
3275 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003276 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003277
3278 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003279 const int32_t hw_w = hw->getWidth();
3280 const int32_t hw_h = hw->getHeight();
3281 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003282 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003283
Dan Stozac1879002014-05-22 15:59:05 -07003284 // if a default or invalid sourceCrop is passed in, set reasonable values
3285 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3286 !sourceCrop.isValid()) {
3287 sourceCrop.setLeftTop(Point(0, 0));
3288 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3289 }
3290
3291 // ensure that sourceCrop is inside screen
3292 if (sourceCrop.left < 0) {
3293 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3294 }
Dan Stozabe31f442014-06-11 11:20:54 -07003295 if (sourceCrop.right > hw_w) {
3296 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003297 }
3298 if (sourceCrop.top < 0) {
3299 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3300 }
Dan Stozabe31f442014-06-11 11:20:54 -07003301 if (sourceCrop.bottom > hw_h) {
3302 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003303 }
3304
Mathias Agopian180f10d2013-04-10 22:55:41 -07003305 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003306 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003307
3308 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003309 engine.setViewportAndProjection(
3310 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003311 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003312
3313 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003314 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003315
3316 const LayerVector& layers( mDrawingState.layersSortedByZ );
3317 const size_t count = layers.size();
3318 for (size_t i=0 ; i<count ; ++i) {
3319 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003320 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003321 if (state.layerStack == hw->getLayerStack()) {
3322 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3323 if (layer->isVisible()) {
3324 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003325 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003326 if (filtering) layer->setFiltering(false);
3327 }
3328 }
3329 }
3330 }
3331
Mathias Agopian931bda12013-08-28 18:11:46 -07003332 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003333}
3334
3335
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003336status_t SurfaceFlinger::captureScreenImplLocked(
3337 const sp<const DisplayDevice>& hw,
3338 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003339 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003340 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003341 bool useIdentityTransform, Transform::orientation_flags rotation,
3342 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003343{
3344 ATRACE_CALL();
3345
Mathias Agopian180f10d2013-04-10 22:55:41 -07003346 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003347 uint32_t hw_w = hw->getWidth();
3348 uint32_t hw_h = hw->getHeight();
3349
3350 if (rotation & Transform::ROT_90) {
3351 std::swap(hw_w, hw_h);
3352 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003353
Mathias Agopian180f10d2013-04-10 22:55:41 -07003354 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3355 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3356 reqWidth, reqHeight, hw_w, hw_h);
3357 return BAD_VALUE;
3358 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003359
Mathias Agopian180f10d2013-04-10 22:55:41 -07003360 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3361 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3362
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003363 bool secureLayerIsVisible = false;
3364 const LayerVector& layers(mDrawingState.layersSortedByZ);
3365 const size_t count = layers.size();
3366 for (size_t i = 0 ; i < count ; ++i) {
3367 const sp<Layer>& layer(layers[i]);
3368 const Layer::State& state(layer->getDrawingState());
3369 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3370 state.z <= maxLayerZ && layer->isVisible() &&
3371 layer->isSecure()) {
3372 secureLayerIsVisible = true;
3373 }
3374 }
3375
3376 if (!isLocalScreenshot && secureLayerIsVisible) {
3377 ALOGW("FB is protected: PERMISSION_DENIED");
3378 return PERMISSION_DENIED;
3379 }
3380
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003381 // create a surface (because we're a producer, and we need to
3382 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003383 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003384 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003385
Michael Lentine5a16a622015-05-21 13:48:24 -07003386 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3387 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003388 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3389 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003390
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003391 int err = 0;
3392 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003393 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003394 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3395 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003396
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003397 if (err == NO_ERROR) {
3398 ANativeWindowBuffer* buffer;
3399 /* TODO: Once we have the sync framework everywhere this can use
3400 * server-side waits on the fence that dequeueBuffer returns.
3401 */
3402 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3403 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003404 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003405 // create an EGLImage from the buffer so we can later
3406 // turn it into a texture
3407 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3408 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3409 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003410 // this binds the given EGLImage as a framebuffer for the
3411 // duration of this scope.
3412 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3413 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003414 // this will in fact render into our dequeued buffer
3415 // via an FBO, which means we didn't have to create
3416 // an EGLSurface and therefore we're not
3417 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003418 renderScreenImplLocked(
3419 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3420 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003421
Riley Andrews86639902014-08-15 12:27:24 -07003422 // Attempt to create a sync khr object that can produce a sync point. If that
3423 // isn't available, create a non-dupable sync object in the fallback path and
3424 // wait on it directly.
3425 EGLSyncKHR sync;
3426 if (!DEBUG_SCREENSHOTS) {
3427 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003428 // native fence fd will not be populated until flush() is done.
3429 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003430 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003431 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003432 }
Riley Andrews86639902014-08-15 12:27:24 -07003433 if (sync != EGL_NO_SYNC_KHR) {
3434 // get the sync fd
3435 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3436 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3437 ALOGW("captureScreen: failed to dup sync khr object");
3438 syncFd = -1;
3439 }
3440 eglDestroySyncKHR(mEGLDisplay, sync);
3441 } else {
3442 // fallback path
3443 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3444 if (sync != EGL_NO_SYNC_KHR) {
3445 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3446 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3447 EGLint eglErr = eglGetError();
3448 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3449 ALOGW("captureScreen: fence wait timed out");
3450 } else {
3451 ALOGW_IF(eglErr != EGL_SUCCESS,
3452 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3453 }
3454 eglDestroySyncKHR(mEGLDisplay, sync);
3455 } else {
3456 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3457 }
3458 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003459 if (DEBUG_SCREENSHOTS) {
3460 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3461 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3462 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3463 hw, minLayerZ, maxLayerZ);
3464 delete [] pixels;
3465 }
3466
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003467 } else {
3468 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3469 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003470 window->cancelBuffer(window, buffer, syncFd);
3471 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003472 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003473 // destroy our image
3474 eglDestroyImageKHR(mEGLDisplay, image);
3475 } else {
3476 result = BAD_VALUE;
3477 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003478 if (buffer) {
3479 // queueBuffer takes ownership of syncFd
3480 result = window->queueBuffer(window, buffer, syncFd);
3481 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003482 }
3483 } else {
3484 result = BAD_VALUE;
3485 }
3486 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3487 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003488
Mathias Agopian74c40c02010-09-29 13:02:36 -07003489 return result;
3490}
3491
Mathias Agopiand5556842013-09-19 17:08:37 -07003492void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3493 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003494 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003495 for (size_t y=0 ; y<h ; y++) {
3496 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3497 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003498 if (p[x] != 0xFF000000) return;
3499 }
3500 }
3501 ALOGE("*** we just took a black screenshot ***\n"
3502 "requested minz=%d, maxz=%d, layerStack=%d",
3503 minLayerZ, maxLayerZ, hw->getLayerStack());
3504 const LayerVector& layers( mDrawingState.layersSortedByZ );
3505 const size_t count = layers.size();
3506 for (size_t i=0 ; i<count ; ++i) {
3507 const sp<Layer>& layer(layers[i]);
3508 const Layer::State& state(layer->getDrawingState());
3509 const bool visible = (state.layerStack == hw->getLayerStack())
3510 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3511 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003512 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003513 visible ? '+' : '-',
3514 i, layer->getName().string(), state.layerStack, state.z,
3515 layer->isVisible(), state.flags, state.alpha);
3516 }
3517 }
3518}
3519
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003520// ---------------------------------------------------------------------------
3521
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003522SurfaceFlinger::LayerVector::LayerVector() {
3523}
3524
3525SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003526 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003527}
3528
3529int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3530 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003531{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003532 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003533 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3534 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003535
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003536 uint32_t ls = l->getCurrentState().layerStack;
3537 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003538 if (ls != rs)
3539 return ls - rs;
3540
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003541 uint32_t lz = l->getCurrentState().z;
3542 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003543 if (lz != rz)
3544 return lz - rz;
3545
3546 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003547}
3548
3549// ---------------------------------------------------------------------------
3550
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003551SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003552 : type(DisplayDevice::DISPLAY_ID_INVALID),
3553 layerStack(DisplayDevice::NO_LAYER_STACK),
3554 orientation(0),
3555 width(0),
3556 height(0),
3557 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003558}
3559
Pablo Ceballos53390e12015-08-04 11:25:59 -07003560SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3561 DisplayDevice::DisplayType type, bool isSecure)
3562 : type(type),
3563 layerStack(DisplayDevice::NO_LAYER_STACK),
3564 orientation(0),
3565 width(0),
3566 height(0),
3567 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003568 viewport.makeInvalid();
3569 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003570}
3571
3572// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003573
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003575
3576
3577#if defined(__gl_h_)
3578#error "don't include gl/gl.h in this file"
3579#endif
3580
3581#if defined(__gl2_h_)
3582#error "don't include gl2/gl2.h in this file"
3583#endif