blob: c09920cd2e55751b89eb6645ac4646ae038b23c6 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700155 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
160 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161{
Steve Blocka19954a2012-01-04 20:05:49 +0000162 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163
164 // debugging stuff...
165 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700166
Mathias Agopianb4b17302013-03-20 18:36:41 -0700167 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700168 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700169
Dan Stoza14cd37c2015-07-09 12:43:33 -0700170 property_get("debug.sf.drop_missed_frames", value, "0");
171 mDropMissedFrames = atoi(value);
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173 property_get("debug.sf.showupdates", value, "0");
174 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700175
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700176 property_get("debug.sf.ddms", value, "0");
177 mDebugDDMS = atoi(value);
178 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700179 if (!startDdmConnection()) {
180 // start failed, and DDMS debugging not enabled
181 mDebugDDMS = 0;
182 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700183 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700184 ALOGI_IF(mDebugRegion, "showupdates enabled");
185 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186}
187
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800188void SurfaceFlinger::onFirstRef()
189{
190 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800191}
192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800193SurfaceFlinger::~SurfaceFlinger()
194{
Mathias Agopiana4912602012-07-12 14:25:33 -0700195 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
196 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
197 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198}
199
Dan Stozac7014012014-02-14 15:03:43 -0800200void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800201{
202 // the window manager died on us. prepare its eulogy.
203
Andy McFadden13a082e2012-08-24 10:16:42 -0700204 // restore initial conditions (default device unblank, etc)
205 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800206
207 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700208 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800209}
210
Mathias Agopian7e27f052010-05-28 14:22:23 -0700211sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212{
Mathias Agopian96f08192010-06-02 23:28:45 -0700213 sp<ISurfaceComposerClient> bclient;
214 sp<Client> client(new Client(this));
215 status_t err = client->initCheck();
216 if (err == NO_ERROR) {
217 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800219 return bclient;
220}
221
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700222sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
223 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700224{
225 class DisplayToken : public BBinder {
226 sp<SurfaceFlinger> flinger;
227 virtual ~DisplayToken() {
228 // no more references, this display must be terminated
229 Mutex::Autolock _l(flinger->mStateLock);
230 flinger->mCurrentState.displays.removeItem(this);
231 flinger->setTransactionFlags(eDisplayTransactionNeeded);
232 }
233 public:
234 DisplayToken(const sp<SurfaceFlinger>& flinger)
235 : flinger(flinger) {
236 }
237 };
238
239 sp<BBinder> token = new DisplayToken(this);
240
241 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700242 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700243 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700244 mCurrentState.displays.add(token, info);
245
246 return token;
247}
248
Jesse Hall6c913be2013-08-08 12:15:49 -0700249void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
250 Mutex::Autolock _l(mStateLock);
251
252 ssize_t idx = mCurrentState.displays.indexOfKey(display);
253 if (idx < 0) {
254 ALOGW("destroyDisplay: invalid display token");
255 return;
256 }
257
258 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
259 if (!info.isVirtualDisplay()) {
260 ALOGE("destroyDisplay called for non-virtual display");
261 return;
262 }
263
264 mCurrentState.displays.removeItemsAt(idx);
265 setTransactionFlags(eDisplayTransactionNeeded);
266}
267
Jesse Hall692c7232012-11-08 15:41:56 -0800268void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800269 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800270 ALOGW_IF(mBuiltinDisplays[type],
271 "Overwriting display token for display type %d", type);
272 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800273 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700274 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800275 mCurrentState.displays.add(mBuiltinDisplays[type], info);
276}
277
Mathias Agopiane57f2922012-08-09 16:29:12 -0700278sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700279 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
281 return NULL;
282 }
Jesse Hall692c7232012-11-08 15:41:56 -0800283 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284}
285
Jamie Gennis9a78c902011-01-12 18:30:40 -0800286sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
287{
288 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
289 return gba;
290}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700291
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800292void SurfaceFlinger::bootFinished()
293{
294 const nsecs_t now = systemTime();
295 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000296 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700297 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700298
299 // wait patiently for the window manager death
300 const String16 name("window");
301 sp<IBinder> window(defaultServiceManager()->getService(name));
302 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700303 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700304 }
305
306 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700307 // formerly we would just kill the process, but we now ask it to exit so it
308 // can choose where to stop the animation.
309 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700310
311 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
312 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
313 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314}
315
Mathias Agopian3f844832013-08-07 21:24:32 -0700316void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700317 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700318 RenderEngine& engine;
319 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700320 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700321 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
322 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700323 }
324 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700326 return true;
327 }
328 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700329 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330}
331
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700332class DispSyncSource : public VSyncSource, private DispSync::Callback {
333public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700334 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000335 const char* name) :
336 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700337 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700338 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000339 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
340 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700341 mDispSync(dispSync),
342 mCallbackMutex(),
343 mCallback(),
344 mVsyncMutex(),
345 mPhaseOffset(phaseOffset),
346 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700347
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700348 virtual ~DispSyncSource() {}
349
350 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700351 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000353 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error registering vsync callback: %s (%d)",
357 strerror(-err), err);
358 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700359 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700360 } else {
361 status_t err = mDispSync->removeEventListener(
362 static_cast<DispSync::Callback*>(this));
363 if (err != NO_ERROR) {
364 ALOGE("error unregistering vsync callback: %s (%d)",
365 strerror(-err), err);
366 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700367 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700369 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700370 }
371
372 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700373 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 mCallback = callback;
375 }
376
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700377 virtual void setPhaseOffset(nsecs_t phaseOffset) {
378 Mutex::Autolock lock(mVsyncMutex);
379
380 // Normalize phaseOffset to [0, period)
381 auto period = mDispSync->getPeriod();
382 phaseOffset %= period;
383 if (phaseOffset < 0) {
384 // If we're here, then phaseOffset is in (-period, 0). After this
385 // operation, it will be in (0, period)
386 phaseOffset += period;
387 }
388 mPhaseOffset = phaseOffset;
389
390 // If we're not enabled, we don't need to mess with the listeners
391 if (!mEnabled) {
392 return;
393 }
394
395 // Remove the listener with the old offset
396 status_t err = mDispSync->removeEventListener(
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error unregistering vsync callback: %s (%d)",
400 strerror(-err), err);
401 }
402
403 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000404 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700405 static_cast<DispSync::Callback*>(this));
406 if (err != NO_ERROR) {
407 ALOGE("error registering vsync callback: %s (%d)",
408 strerror(-err), err);
409 }
410 }
411
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412private:
413 virtual void onDispSyncEvent(nsecs_t when) {
414 sp<VSyncSource::Callback> callback;
415 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700416 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 callback = mCallback;
418
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700419 if (mTraceVsync) {
420 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700421 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700422 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700423 }
424
425 if (callback != NULL) {
426 callback->onVSyncEvent(when);
427 }
428 }
429
Tim Murray4a4e4a22016-04-19 16:29:23 +0000430 const char* const mName;
431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 int mValue;
433
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700434 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700435 const String8 mVsyncOnLabel;
436 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700437
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439
440 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700442
443 Mutex mVsyncMutex; // Protects the following
444 nsecs_t mPhaseOffset;
445 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446};
447
448void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700449 ALOGI( "SurfaceFlinger's main thread ready to run. "
450 "Initializing graphics H/W...");
451
Dan Stoza9e56aa02015-11-02 13:00:03 -0800452 { // Autolock scope
453 Mutex::Autolock _l(mStateLock);
454
455 // initialize EGL for the default display
456 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
457 eglInitialize(mEGLDisplay, NULL, NULL);
458
459 // start the EventThread
460 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
461 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000462 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800463 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
464 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800466 mEventQueue.setEventThread(mSFEventThread);
467
468 // Get a RenderEngine for the given display / config (can't fail)
469 mRenderEngine = RenderEngine::create(mEGLDisplay,
470 HAL_PIXEL_FORMAT_RGBA_8888);
471 }
472
473 // Drop the state lock while we initialize the hardware composer. We drop
474 // the lock because on creation, it will call back into SurfaceFlinger to
475 // initialize the primary display.
476 mHwc = new HWComposer(this);
477 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
478
Jesse Hall692c7232012-11-08 15:41:56 -0800479 Mutex::Autolock _l(mStateLock);
480
Mathias Agopian875d8e12013-06-07 15:35:48 -0700481 // retrieve the EGL context that was selected/created
482 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700483
Mathias Agopianda27af92012-09-13 18:17:13 -0700484 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
485 "couldn't create EGLContext");
486
Dan Stoza9e56aa02015-11-02 13:00:03 -0800487 // make the GLContext current so that we can create textures when creating
488 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700489 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
490
Jamie Gennisd1700752013-10-14 12:22:52 -0700491 mEventControlThread = new EventControlThread(this);
492 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
493
Mathias Agopian92a979a2012-08-02 18:32:23 -0700494 // initialize our drawing state
495 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700496
Andy McFadden13a082e2012-08-24 10:16:42 -0700497 // set initial conditions (e.g. unblank default device)
498 initializeDisplays();
499
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700500 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700501 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502
Dan Stoza9e56aa02015-11-02 13:00:03 -0800503 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700504}
505
Mathias Agopiana67e4182012-06-19 17:26:12 -0700506void SurfaceFlinger::startBootAnim() {
507 // start boot animation
508 property_set("service.bootanim.exit", "0");
509 property_set("ctl.start", "bootanim");
510}
511
Mathias Agopian875d8e12013-06-07 15:35:48 -0700512size_t SurfaceFlinger::getMaxTextureSize() const {
513 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700514}
515
Mathias Agopian875d8e12013-06-07 15:35:48 -0700516size_t SurfaceFlinger::getMaxViewportDims() const {
517 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700518}
519
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800521
Jamie Gennis582270d2011-08-17 18:19:00 -0700522bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800523 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800524 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800525 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700526 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800527}
528
Dan Stoza7f7da322014-05-02 15:26:25 -0700529status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
530 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700531 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700532 return BAD_VALUE;
533 }
534
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500535 if (!display.get())
536 return NAME_NOT_FOUND;
537
Jesse Hall692c7232012-11-08 15:41:56 -0800538 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700539 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800540 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700541 type = i;
542 break;
543 }
544 }
545
546 if (type < 0) {
547 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700548 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700549
Mathias Agopian8b736f12012-08-13 17:54:26 -0700550 // TODO: Not sure if display density should handled by SF any longer
551 class Density {
552 static int getDensityFromProperty(char const* propName) {
553 char property[PROPERTY_VALUE_MAX];
554 int density = 0;
555 if (property_get(propName, property, NULL) > 0) {
556 density = atoi(property);
557 }
558 return density;
559 }
560 public:
561 static int getEmuDensity() {
562 return getDensityFromProperty("qemu.sf.lcd_density"); }
563 static int getBuildDensity() {
564 return getDensityFromProperty("ro.sf.lcd_density"); }
565 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700566
Dan Stoza7f7da322014-05-02 15:26:25 -0700567 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700568
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700570 DisplayInfo info = DisplayInfo();
571
Dan Stoza9e56aa02015-11-02 13:00:03 -0800572 float xdpi = hwConfig->getDpiX();
573 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700574
575 if (type == DisplayDevice::DISPLAY_PRIMARY) {
576 // The density of the device is provided by a build property
577 float density = Density::getBuildDensity() / 160.0f;
578 if (density == 0) {
579 // the build doesn't provide a density -- this is wrong!
580 // use xdpi instead
581 ALOGE("ro.sf.lcd_density must be defined as a build property");
582 density = xdpi / 160.0f;
583 }
584 if (Density::getEmuDensity()) {
585 // if "qemu.sf.lcd_density" is specified, it overrides everything
586 xdpi = ydpi = density = Density::getEmuDensity();
587 density /= 160.0f;
588 }
589 info.density = density;
590
591 // TODO: this needs to go away (currently needed only by webkit)
592 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
593 info.orientation = hw->getOrientation();
594 } else {
595 // TODO: where should this value come from?
596 static const int TV_DENSITY = 213;
597 info.density = TV_DENSITY / 160.0f;
598 info.orientation = 0;
599 }
600
Dan Stoza9e56aa02015-11-02 13:00:03 -0800601 info.w = hwConfig->getWidth();
602 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700603 info.xdpi = xdpi;
604 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700606 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800607
608 // TODO: Hook this back up
609 info.colorTransform = 0;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700610
611 // This is how far in advance a buffer must be queued for
612 // presentation at a given time. If you want a buffer to appear
613 // on the screen at time N, you must submit the buffer before
614 // (N - presentationDeadline).
615 //
616 // Normally it's one full refresh period (to give SF a chance to
617 // latch the buffer), but this can be reduced by configuring a
618 // DispSync offset. Any additional delays introduced by the hardware
619 // composer or panel must be accounted for here.
620 //
621 // We add an additional 1ms to allow for processing time and
622 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800623 info.presentationDeadline = hwConfig->getVsyncPeriod() -
624 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700625
626 // All non-virtual displays are currently considered secure.
627 info.secure = true;
628
629 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700630 }
631
Dan Stoza7f7da322014-05-02 15:26:25 -0700632 return NO_ERROR;
633}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700634
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800635status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700636 DisplayStatInfo* stats) {
637 if (stats == NULL) {
638 return BAD_VALUE;
639 }
640
641 // FIXME for now we always return stats for the primary display
642 memset(stats, 0, sizeof(*stats));
643 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
644 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
645 return NO_ERROR;
646}
647
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700648int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700649 sp<DisplayDevice> device(getDisplayDevice(display));
650 if (device != NULL) {
651 return device->getActiveConfig();
652 }
653 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700654}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700655
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700656void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
657 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
658 this);
659 int32_t type = hw->getDisplayType();
660 int currentMode = hw->getActiveConfig();
661
662 if (mode == currentMode) {
663 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
664 return;
665 }
666
667 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
668 ALOGW("Trying to set config for virtual display");
669 return;
670 }
671
672 hw->setActiveConfig(mode);
673 getHwComposer().setActiveConfig(type, mode);
674}
675
676status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
677 class MessageSetActiveConfig: public MessageBase {
678 SurfaceFlinger& mFlinger;
679 sp<IBinder> mDisplay;
680 int mMode;
681 public:
682 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
683 int mode) :
684 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
685 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700686 Vector<DisplayInfo> configs;
687 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700688 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700689 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700690 mMode, configs.size());
691 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700692 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
693 if (hw == NULL) {
694 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700695 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700696 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
697 ALOGW("Attempt to set active config = %d for virtual display",
698 mMode);
699 } else {
700 mFlinger.setActiveConfigInternal(hw, mMode);
701 }
702 return true;
703 }
704 };
705 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
706 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700707 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700708}
709
Svetoslavd85084b2014-03-20 10:28:31 -0700710status_t SurfaceFlinger::clearAnimationFrameStats() {
711 Mutex::Autolock _l(mStateLock);
712 mAnimFrameTracker.clearStats();
713 return NO_ERROR;
714}
715
716status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
717 Mutex::Autolock _l(mStateLock);
718 mAnimFrameTracker.getStats(outStats);
719 return NO_ERROR;
720}
721
Dan Stozac4f471e2016-03-24 09:31:08 -0700722status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
723 HdrCapabilities* outCapabilities) const {
724 Mutex::Autolock _l(mStateLock);
725
726 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
727 if (displayDevice == nullptr) {
728 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
729 return BAD_VALUE;
730 }
731
732 std::unique_ptr<HdrCapabilities> capabilities =
733 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
734 if (capabilities) {
735 std::swap(*outCapabilities, *capabilities);
736 } else {
737 return BAD_VALUE;
738 }
739
740 return NO_ERROR;
741}
742
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800743// ----------------------------------------------------------------------------
744
745sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800746 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700747}
748
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800749// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800750
751void SurfaceFlinger::waitForEvent() {
752 mEventQueue.waitMessage();
753}
754
755void SurfaceFlinger::signalTransaction() {
756 mEventQueue.invalidate();
757}
758
759void SurfaceFlinger::signalLayerUpdate() {
760 mEventQueue.invalidate();
761}
762
763void SurfaceFlinger::signalRefresh() {
764 mEventQueue.refresh();
765}
766
767status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800768 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800769 return mEventQueue.postMessage(msg, reltime);
770}
771
772status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800773 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800774 status_t res = mEventQueue.postMessage(msg, reltime);
775 if (res == NO_ERROR) {
776 msg->wait();
777 }
778 return res;
779}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700781void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700782 do {
783 waitForEvent();
784 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800785}
786
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700787void SurfaceFlinger::enableHardwareVsync() {
788 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700789 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700790 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700791 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
792 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700793 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700794 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700795}
796
Jesse Hall948fe0c2013-10-14 12:56:09 -0700797void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700798 Mutex::Autolock _l(mHWVsyncLock);
799
Jesse Hall948fe0c2013-10-14 12:56:09 -0700800 if (makeAvailable) {
801 mHWVsyncAvailable = true;
802 } else if (!mHWVsyncAvailable) {
803 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
804 return;
805 }
806
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
808 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700809
810 mPrimaryDispSync.reset();
811 mPrimaryDispSync.setPeriod(period);
812
813 if (!mPrimaryHWVsyncEnabled) {
814 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700815 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
816 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700817 mPrimaryHWVsyncEnabled = true;
818 }
819}
820
Jesse Hall948fe0c2013-10-14 12:56:09 -0700821void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700822 Mutex::Autolock _l(mHWVsyncLock);
823 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700824 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
825 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700826 mPrimaryDispSync.endResync();
827 mPrimaryHWVsyncEnabled = false;
828 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700829 if (makeUnavailable) {
830 mHWVsyncAvailable = false;
831 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700832}
833
Tim Murray4a4e4a22016-04-19 16:29:23 +0000834void SurfaceFlinger::resyncWithRateLimit() {
835 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
836 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
837 resyncToHardwareVsync(true);
838 }
839}
840
Dan Stoza9e56aa02015-11-02 13:00:03 -0800841void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700842 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700843
Jamie Gennisd1700752013-10-14 12:22:52 -0700844 { // Scope for the lock
845 Mutex::Autolock _l(mHWVsyncLock);
846 if (type == 0 && mPrimaryHWVsyncEnabled) {
847 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700848 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700849 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700850
851 if (needsHwVsync) {
852 enableHardwareVsync();
853 } else {
854 disableHardwareVsync(false);
855 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700856}
857
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
859 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
860 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
861 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700862
Dan Stoza9e56aa02015-11-02 13:00:03 -0800863 // All non-virtual displays are currently considered secure.
864 bool isSecure = true;
865
866 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
867 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
868 wp<IBinder> token = mBuiltinDisplays[type];
869
870 sp<IGraphicBufferProducer> producer;
871 sp<IGraphicBufferConsumer> consumer;
872 BufferQueue::createBufferQueue(&producer, &consumer,
873 new GraphicBufferAlloc());
874
875 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
876 DisplayDevice::DISPLAY_PRIMARY, consumer);
877 sp<DisplayDevice> hw = new DisplayDevice(this,
878 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
879 producer, mRenderEngine->getEGLConfig());
880 mDisplays.add(token, hw);
881 } else {
882 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700883 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800884 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700886 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800887 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
888 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700889 }
890 setTransactionFlags(eDisplayTransactionNeeded);
891
Andy McFadden9e9689c2012-10-10 18:17:51 -0700892 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700893 }
Mathias Agopian86303202012-07-24 22:46:10 -0700894}
895
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700897 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898 getHwComposer().setVsyncEnabled(disp,
899 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700900}
901
Mathias Agopian4fec8732012-06-29 14:12:52 -0700902void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800903 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800904 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800905 case MessageQueue::TRANSACTION: {
906 handleMessageTransaction();
907 break;
908 }
909 case MessageQueue::INVALIDATE: {
910 bool refreshNeeded = handleMessageTransaction();
911 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800912 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800913 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800914 // Signal a refresh if a transaction modified the window state,
915 // a new buffer was latched, or if HWC has requested a full
916 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800917 signalRefresh();
918 }
919 break;
920 }
921 case MessageQueue::REFRESH: {
922 handleMessageRefresh();
923 break;
924 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800925 }
926}
927
Dan Stoza6b9454d2014-11-07 16:00:59 -0800928bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700929 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700930 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700931 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800932 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700933 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800934 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700935}
936
Dan Stoza6b9454d2014-11-07 16:00:59 -0800937bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700938 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800939 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700940}
941
942void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700943 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700944
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700945#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -0800946 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700947#else
948 nsecs_t refreshStartTime = 0;
949#endif
Dan Stoza14cd37c2015-07-09 12:43:33 -0700950 static nsecs_t previousExpectedPresent = 0;
951 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
952 static bool previousFrameMissed = false;
953 bool frameMissed = (expectedPresent == previousExpectedPresent);
954 if (frameMissed != previousFrameMissed) {
955 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
956 }
957 previousFrameMissed = frameMissed;
958
959 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
960 // Latch buffers, but don't send anything to HWC, then signal another
961 // wakeup for the next vsync
962 preComposition();
963 repaintEverything();
964 } else {
965 preComposition();
966 rebuildLayerStacks();
967 setUpHWComposer();
968 doDebugFlashRegions();
969 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800970 postComposition(refreshStartTime);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700971 }
972
Dan Stoza9e56aa02015-11-02 13:00:03 -0800973 // Release any buffers which were replaced this frame
974 for (auto& layer : mLayersWithQueuedFrames) {
975 layer->releasePendingBuffer();
976 }
977 mLayersWithQueuedFrames.clear();
978
Dan Stoza14cd37c2015-07-09 12:43:33 -0700979 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700980}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700981
Mathias Agopiancd60f992012-08-16 16:28:27 -0700982void SurfaceFlinger::doDebugFlashRegions()
983{
984 // is debugging enabled
985 if (CC_LIKELY(!mDebugRegion))
986 return;
987
988 const bool repaintEverything = mRepaintEverything;
989 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
990 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700991 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700992 // transform the dirty region into this screen's coordinate space
993 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
994 if (!dirtyRegion.isEmpty()) {
995 // redraw the whole screen
996 doComposeSurfaces(hw, Region(hw->bounds()));
997
998 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -0700999 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001000 RenderEngine& engine(getRenderEngine());
1001 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1002
Mathias Agopianda27af92012-09-13 18:17:13 -07001003 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001004 }
1005 }
1006 }
1007
1008 postFramebuffer();
1009
1010 if (mDebugRegion > 1) {
1011 usleep(mDebugRegion * 1000);
1012 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001013
Dan Stoza9e56aa02015-11-02 13:00:03 -08001014 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1015 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1016 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1017 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001018 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001019}
1020
1021void SurfaceFlinger::preComposition()
1022{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001023 ATRACE_CALL();
1024 ALOGV("preComposition");
1025
Mathias Agopiancd60f992012-08-16 16:28:27 -07001026 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001027 const LayerVector& layers(mDrawingState.layersSortedByZ);
1028 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001029 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001030 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001031 needExtraInvalidate = true;
1032 }
1033 }
1034 if (needExtraInvalidate) {
1035 signalLayerUpdate();
1036 }
1037}
1038
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001039#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001040void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001041#else
1042void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1043#endif
Mathias Agopiancd60f992012-08-16 16:28:27 -07001044{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001045 ATRACE_CALL();
1046 ALOGV("postComposition");
1047
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001048 const LayerVector& layers(mDrawingState.layersSortedByZ);
1049 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001050 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001051 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001052 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001053
Dan Stoza9e56aa02015-11-02 13:00:03 -08001054 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001055
1056 if (presentFence->isValid()) {
1057 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1058 enableHardwareVsync();
1059 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001060 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001061 }
1062 }
1063
Dan Stozab90cf072015-03-05 11:05:59 -08001064 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001065 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001066 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001067 enableHardwareVsync();
1068 }
1069 }
1070
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001071#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001072 mFenceTracker.addFrame(refreshStartTime, presentFence,
1073 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001074#endif
Pablo Ceballos40845df2016-01-25 17:41:15 -08001075
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001076 if (mAnimCompositionPending) {
1077 mAnimCompositionPending = false;
1078
Jesse Halla9a1b002013-02-27 16:39:25 -08001079 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001080 mAnimFrameTracker.setActualPresentFence(presentFence);
1081 } else {
1082 // The HWC doesn't support present fences, so use the refresh
1083 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001084 nsecs_t presentTime =
1085 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001086 mAnimFrameTracker.setActualPresentTime(presentTime);
1087 }
1088 mAnimFrameTracker.advanceFrame();
1089 }
Dan Stozab90cf072015-03-05 11:05:59 -08001090
1091 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1092 return;
1093 }
1094
1095 nsecs_t currentTime = systemTime();
1096 if (mHasPoweredOff) {
1097 mHasPoweredOff = false;
1098 } else {
1099 nsecs_t period = mPrimaryDispSync.getPeriod();
1100 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1101 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1102 if (numPeriods < NUM_BUCKETS - 1) {
1103 mFrameBuckets[numPeriods] += elapsedTime;
1104 } else {
1105 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1106 }
1107 mTotalTime += elapsedTime;
1108 }
1109 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001110}
1111
1112void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001113 ATRACE_CALL();
1114 ALOGV("rebuildLayerStacks");
1115
Mathias Agopiancd60f992012-08-16 16:28:27 -07001116 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001117 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001118 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001119 mVisibleRegionsDirty = false;
1120 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001121
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001122 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001123 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001124 Region opaqueRegion;
1125 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001126 Vector<sp<Layer>> layersSortedByZ;
1127 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1128 const Transform& tr(displayDevice->getTransform());
1129 const Rect bounds(displayDevice->getBounds());
1130 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001131 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 displayDevice->getLayerStack(), dirtyRegion,
1133 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001134
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001135 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001136 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001137 const sp<Layer>& layer(layers[i]);
1138 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001139 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001140 Region drawRegion(tr.transform(
1141 layer->visibleNonTransparentRegion));
1142 drawRegion.andSelf(bounds);
1143 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001144 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001145 } else {
1146 // Clear out the HWC layer if this layer was
1147 // previously visible, but no longer is
1148 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1149 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001150 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001151 }
1152 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001153 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001154 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1155 displayDevice->undefinedRegion.set(bounds);
1156 displayDevice->undefinedRegion.subtractSelf(
1157 tr.transform(opaqueRegion));
1158 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001159 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001160 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001161}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001162
Mathias Agopiancd60f992012-08-16 16:28:27 -07001163void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001164 ATRACE_CALL();
1165 ALOGV("setUpHWComposer");
1166
Jesse Hall028dc8f2013-08-20 16:35:32 -07001167 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001168 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1169 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1170 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1171
1172 // If nothing has changed (!dirty), don't recompose.
1173 // If something changed, but we don't currently have any visible layers,
1174 // and didn't when we last did a composition, then skip it this time.
1175 // The second rule does two things:
1176 // - When all layers are removed from a display, we'll emit one black
1177 // frame, then nothing more until we get new layers.
1178 // - When a display is created with a private layer stack, we won't
1179 // emit any black frames until a layer is added to the layer stack.
1180 bool mustRecompose = dirty && !(empty && wasEmpty);
1181
1182 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1183 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1184 mustRecompose ? "doing" : "skipping",
1185 dirty ? "+" : "-",
1186 empty ? "+" : "-",
1187 wasEmpty ? "+" : "-");
1188
Dan Stoza71433162014-02-04 16:22:36 -08001189 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001190
1191 if (mustRecompose) {
1192 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1193 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001194 }
1195
Dan Stoza9e56aa02015-11-02 13:00:03 -08001196 // build the h/w work list
1197 if (CC_UNLIKELY(mGeometryInvalid)) {
1198 mGeometryInvalid = false;
1199 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1200 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1201 const auto hwcId = displayDevice->getHwcDisplayId();
1202 if (hwcId >= 0) {
1203 const Vector<sp<Layer>>& currentLayers(
1204 displayDevice->getVisibleLayersSortedByZ());
1205 bool foundLayerWithoutHwc = false;
1206 for (auto& layer : currentLayers) {
1207 if (!layer->hasHwcLayer(hwcId)) {
1208 auto hwcLayer = mHwc->createLayer(hwcId);
1209 if (hwcLayer) {
1210 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1211 } else {
1212 layer->forceClientComposition(hwcId);
1213 foundLayerWithoutHwc = true;
1214 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001215 }
1216 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001217
Dan Stoza9e56aa02015-11-02 13:00:03 -08001218 layer->setGeometry(displayDevice);
1219 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1220 mHasColorMatrix) {
1221 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001222 }
1223 }
1224 }
1225 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001226 }
Riley Andrews03414a12014-07-01 14:22:59 -07001227
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 // Set the per-frame data
1229 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1230 auto& displayDevice = mDisplays[displayId];
1231 const auto hwcId = displayDevice->getHwcDisplayId();
1232 if (hwcId < 0) {
1233 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001234 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001235 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1236 layer->setPerFrameData(displayDevice);
1237 }
1238 }
1239
1240 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1241 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1242 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1243 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001244 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001245}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001246
Mathias Agopiancd60f992012-08-16 16:28:27 -07001247void SurfaceFlinger::doComposition() {
1248 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 ALOGV("doComposition");
1250
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001251 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001252 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001253 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001254 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001255 // transform the dirty region into this screen's coordinate space
1256 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001257
1258 // repaint the framebuffer (if needed)
1259 doDisplayComposition(hw, dirtyRegion);
1260
Mathias Agopiancd60f992012-08-16 16:28:27 -07001261 hw->dirtyRegion.clear();
1262 hw->flip(hw->swapRegion);
1263 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001264 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001265 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001266 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001267}
1268
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001269void SurfaceFlinger::postFramebuffer()
1270{
Mathias Agopian841cde52012-03-01 15:44:37 -08001271 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001273
Mathias Agopiana44b0412011-10-16 18:46:35 -07001274 const nsecs_t now = systemTime();
1275 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001276
Dan Stoza9e56aa02015-11-02 13:00:03 -08001277 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1278 auto& displayDevice = mDisplays[displayId];
1279 const auto hwcId = displayDevice->getHwcDisplayId();
1280 if (hwcId >= 0) {
1281 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001282 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001283 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001284 if (displayId == 0) {
1285 // Make the default display current because the VirtualDisplayDevice
1286 // code cannot deal with dequeueBuffer() being called outside of the
1287 // composition loop; however the code below can call glFlush() which
1288 // is allowed to (and does in some case) call dequeueBuffer().
1289 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1290 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001291 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1292 sp<Fence> releaseFence = Fence::NO_FENCE;
1293 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1294 releaseFence = displayDevice->getClientTargetAcquireFence();
1295 } else {
1296 auto hwcLayer = layer->getHwcLayer(hwcId);
1297 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001298 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299 layer->onLayerDisplayed(releaseFence);
1300 }
1301 if (hwcId >= 0) {
1302 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001303 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001304 }
1305
Mathias Agopiana44b0412011-10-16 18:46:35 -07001306 mLastSwapBufferTime = systemTime() - now;
1307 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001308
1309 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1310 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1311 logFrameStats();
1312 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001313}
1314
Mathias Agopian87baae12012-07-31 12:38:26 -07001315void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001316{
Mathias Agopian841cde52012-03-01 15:44:37 -08001317 ATRACE_CALL();
1318
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001319 // here we keep a copy of the drawing state (that is the state that's
1320 // going to be overwritten by handleTransactionLocked()) outside of
1321 // mStateLock so that the side-effects of the State assignment
1322 // don't happen with mStateLock held (which can cause deadlocks).
1323 State drawingState(mDrawingState);
1324
Mathias Agopianca4d3602011-05-19 15:38:14 -07001325 Mutex::Autolock _l(mStateLock);
1326 const nsecs_t now = systemTime();
1327 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001328
Mathias Agopianca4d3602011-05-19 15:38:14 -07001329 // Here we're guaranteed that some transaction flags are set
1330 // so we can call handleTransactionLocked() unconditionally.
1331 // We call getTransactionFlags(), which will also clear the flags,
1332 // with mStateLock held to guarantee that mCurrentState won't change
1333 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001334
Mathias Agopiane57f2922012-08-09 16:29:12 -07001335 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001336 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001337
Mathias Agopianca4d3602011-05-19 15:38:14 -07001338 mLastTransactionTime = systemTime() - now;
1339 mDebugInTransaction = 0;
1340 invalidateHwcGeometry();
1341 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001342}
1343
Mathias Agopian87baae12012-07-31 12:38:26 -07001344void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001345{
1346 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001347 const size_t count = currentLayers.size();
1348
Dan Stoza7dde5992015-05-22 09:51:44 -07001349 // Notify all layers of available frames
1350 for (size_t i = 0; i < count; ++i) {
1351 currentLayers[i]->notifyAvailableFrames();
1352 }
1353
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354 /*
1355 * Traversal of the children
1356 * (perform the transaction for each of them if needed)
1357 */
1358
Mathias Agopian3559b072012-08-15 13:46:03 -07001359 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001360 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001361 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1363 if (!trFlags) continue;
1364
1365 const uint32_t flags = layer->doTransaction(0);
1366 if (flags & Layer::eVisibleRegion)
1367 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001368 }
1369 }
1370
1371 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001372 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001373 */
1374
Mathias Agopiane57f2922012-08-09 16:29:12 -07001375 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001376 // here we take advantage of Vector's copy-on-write semantics to
1377 // improve performance by skipping the transaction entirely when
1378 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001379 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1380 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001381 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001383 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001384 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001385
1386 // find the displays that were removed
1387 // (ie: in drawing state but not in current state)
1388 // also handle displays that changed
1389 // (ie: displays that are in both lists)
1390 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001391 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1392 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001393 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001394 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001395 // Call makeCurrent() on the primary display so we can
1396 // be sure that nothing associated with this display
1397 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001398 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001399 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001400 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1401 if (hw != NULL)
1402 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001403 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001404 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001405 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001406 } else {
1407 ALOGW("trying to remove the main display");
1408 }
1409 } else {
1410 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001411 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001412 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001413 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1414 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001415 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001416 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001417 // recreating the DisplayDevice, so we just remove it
1418 // from the drawing state, so that it get re-added
1419 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001420 sp<DisplayDevice> hw(getDisplayDevice(display));
1421 if (hw != NULL)
1422 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001423 mDisplays.removeItem(display);
1424 mDrawingState.displays.removeItemsAt(i);
1425 dc--; i--;
1426 // at this point we must loop to the next item
1427 continue;
1428 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001429
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001430 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001431 if (disp != NULL) {
1432 if (state.layerStack != draw[i].layerStack) {
1433 disp->setLayerStack(state.layerStack);
1434 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001435 if ((state.orientation != draw[i].orientation)
1436 || (state.viewport != draw[i].viewport)
1437 || (state.frame != draw[i].frame))
1438 {
1439 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001440 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001441 }
Michael Lentine47e45402014-07-18 15:34:25 -07001442 if (state.width != draw[i].width || state.height != draw[i].height) {
1443 disp->setDisplaySize(state.width, state.height);
1444 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001445 }
1446 }
1447 }
1448
1449 // find displays that were added
1450 // (ie: in current state but not in drawing state)
1451 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001452 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001453 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001454
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001455 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001456 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001457 sp<IGraphicBufferProducer> bqProducer;
1458 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001459 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1460 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001461
Dan Stoza9e56aa02015-11-02 13:00:03 -08001462 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001463 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001464 // Virtual displays without a surface are dormant:
1465 // they have external state (layer stack, projection,
1466 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001467 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001468
Dan Stoza1f3efb12014-10-15 16:34:55 -07001469 int width = 0;
1470 int status = state.surface->query(
1471 NATIVE_WINDOW_WIDTH, &width);
1472 ALOGE_IF(status != NO_ERROR,
1473 "Unable to query width (%d)", status);
1474 int height = 0;
1475 status = state.surface->query(
1476 NATIVE_WINDOW_HEIGHT, &height);
1477 ALOGE_IF(status != NO_ERROR,
1478 "Unable to query height (%d)", status);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001479
Dan Stoza9e56aa02015-11-02 13:00:03 -08001480 mHwc->allocateVirtualDisplay(width, height,
1481 &hwcId);
1482
1483 sp<VirtualDisplaySurface> vds =
1484 new VirtualDisplaySurface(*mHwc,
1485 hwcId, state.surface, bqProducer,
1486 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001487
1488 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001489 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001490 }
1491 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001492 ALOGE_IF(state.surface!=NULL,
1493 "adding a supported display, but rendering "
1494 "surface is provided (%p), ignoring it",
1495 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001496 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1497 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1498 dispSurface = new FramebufferSurface(*mHwc,
1499 DisplayDevice::DISPLAY_EXTERNAL,
1500 bqConsumer);
1501 producer = bqProducer;
1502 } else {
1503 ALOGE("Attempted to add non-external non-virtual"
1504 " display");
1505 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001506 }
1507
1508 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001509 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001510 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001511 state.type, hwcId, state.isSecure, display,
1512 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001513 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001514 hw->setLayerStack(state.layerStack);
1515 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001516 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001517 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001518 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001519 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001520 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001521 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001522 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001523 }
1524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001525 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001526 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001527
Mathias Agopian84300952012-11-21 16:02:13 -08001528 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1529 // The transform hint might have changed for some layers
1530 // (either because a display has changed, or because a layer
1531 // as changed).
1532 //
1533 // Walk through all the layers in currentLayers,
1534 // and update their transform hint.
1535 //
1536 // If a layer is visible only on a single display, then that
1537 // display is used to calculate the hint, otherwise we use the
1538 // default display.
1539 //
1540 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1541 // the hint is set before we acquire a buffer from the surface texture.
1542 //
1543 // NOTE: layer transactions have taken place already, so we use their
1544 // drawing state. However, SurfaceFlinger's own transaction has not
1545 // happened yet, so we must use the current state layer list
1546 // (soon to become the drawing state list).
1547 //
1548 sp<const DisplayDevice> disp;
1549 uint32_t currentlayerStack = 0;
1550 for (size_t i=0; i<count; i++) {
1551 // NOTE: we rely on the fact that layers are sorted by
1552 // layerStack first (so we don't have to traverse the list
1553 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001554 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001555 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001556 if (i==0 || currentlayerStack != layerStack) {
1557 currentlayerStack = layerStack;
1558 // figure out if this layerstack is mirrored
1559 // (more than one display) if so, pick the default display,
1560 // if not, pick the only display it's on.
1561 disp.clear();
1562 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1563 sp<const DisplayDevice> hw(mDisplays[dpy]);
1564 if (hw->getLayerStack() == currentlayerStack) {
1565 if (disp == NULL) {
1566 disp = hw;
1567 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001568 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001569 break;
1570 }
1571 }
1572 }
1573 }
Chet Haase91d25932013-04-11 15:24:55 -07001574 if (disp == NULL) {
1575 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1576 // redraw after transform hint changes. See bug 8508397.
1577
1578 // could be null when this layer is using a layerStack
1579 // that is not visible on any display. Also can occur at
1580 // screen off/on times.
1581 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001582 }
Chet Haase91d25932013-04-11 15:24:55 -07001583 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001584 }
1585 }
1586
1587
Mathias Agopian3559b072012-08-15 13:46:03 -07001588 /*
1589 * Perform our own transaction if needed
1590 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001591
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001592 const LayerVector& layers(mDrawingState.layersSortedByZ);
1593 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001594 // layers have been added
1595 mVisibleRegionsDirty = true;
1596 }
1597
1598 // some layers might have been removed, so
1599 // we need to update the regions they're exposing.
1600 if (mLayersRemoved) {
1601 mLayersRemoved = false;
1602 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001603 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001604 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001605 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001606 if (currentLayers.indexOf(layer) < 0) {
1607 // this layer is not visible anymore
1608 // TODO: we could traverse the tree from front to back and
1609 // compute the actual visible region
1610 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001611 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001612 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001613 Region(Rect(s.active.w, s.active.h)));
1614 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001615 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001616 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001617 }
1618
1619 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001620
1621 updateCursorAsync();
1622}
1623
1624void SurfaceFlinger::updateCursorAsync()
1625{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001626 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1627 auto& displayDevice = mDisplays[displayId];
1628 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001629 continue;
1630 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001631
1632 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1633 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001634 }
1635 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001636}
1637
1638void SurfaceFlinger::commitTransaction()
1639{
1640 if (!mLayersPendingRemoval.isEmpty()) {
1641 // Notify removed layers now that they can't be drawn from
1642 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1643 mLayersPendingRemoval[i]->onRemoved();
1644 }
1645 mLayersPendingRemoval.clear();
1646 }
1647
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001648 // If this transaction is part of a window animation then the next frame
1649 // we composite should be considered an animation as well.
1650 mAnimCompositionPending = mAnimTransactionPending;
1651
Mathias Agopian4fec8732012-06-29 14:12:52 -07001652 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001653 mTransactionPending = false;
1654 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001655 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001656}
1657
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001658void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001659 const LayerVector& currentLayers, uint32_t layerStack,
1660 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001661{
Mathias Agopian841cde52012-03-01 15:44:37 -08001662 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001664
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001665 Region aboveOpaqueLayers;
1666 Region aboveCoveredLayers;
1667 Region dirty;
1668
Mathias Agopian87baae12012-07-31 12:38:26 -07001669 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001670
1671 size_t i = currentLayers.size();
1672 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001673 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001674
1675 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001676 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001677
Jesse Hall01e29052013-02-19 16:13:35 -08001678 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001679 if (s.layerStack != layerStack)
1680 continue;
1681
Mathias Agopianab028732010-03-16 16:41:46 -07001682 /*
1683 * opaqueRegion: area of a surface that is fully opaque.
1684 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001685 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001686
1687 /*
1688 * visibleRegion: area of a surface that is visible on screen
1689 * and not fully transparent. This is essentially the layer's
1690 * footprint minus the opaque regions above it.
1691 * Areas covered by a translucent surface are considered visible.
1692 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001693 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001694
1695 /*
1696 * coveredRegion: area of a surface that is covered by all
1697 * visible regions above it (which includes the translucent areas).
1698 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001699 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001700
Jesse Halla8026d22012-09-25 13:25:04 -07001701 /*
1702 * transparentRegion: area of a surface that is hinted to be completely
1703 * transparent. This is only used to tell when the layer has no visible
1704 * non-transparent regions and can be removed from the layer list. It
1705 * does not affect the visibleRegion of this layer or any layers
1706 * beneath it. The hint may not be correct if apps don't respect the
1707 * SurfaceView restrictions (which, sadly, some don't).
1708 */
1709 Region transparentRegion;
1710
Mathias Agopianab028732010-03-16 16:41:46 -07001711
1712 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001713 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001714 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001715 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001716 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001717 if (!visibleRegion.isEmpty()) {
1718 // Remove the transparent area from the visible region
1719 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001720 const Transform tr(s.active.transform);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001721 if (tr.transformed()) {
1722 if (tr.preserveRects()) {
1723 // transform the transparent region
Mathias Agopian2ca79392013-04-02 18:30:32 -07001724 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001725 } else {
1726 // transformation too complex, can't do the
1727 // transparent region optimization.
Jesse Halla8026d22012-09-25 13:25:04 -07001728 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001729 }
1730 } else {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001731 transparentRegion = s.activeTransparentRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001732 }
Mathias Agopianab028732010-03-16 16:41:46 -07001733 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001734
Mathias Agopianab028732010-03-16 16:41:46 -07001735 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001736 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001737 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001738 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1739 // the opaque region is the layer's footprint
1740 opaqueRegion = visibleRegion;
1741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001742 }
1743 }
1744
Mathias Agopianab028732010-03-16 16:41:46 -07001745 // Clip the covered region to the visible region
1746 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1747
1748 // Update aboveCoveredLayers for next (lower) layer
1749 aboveCoveredLayers.orSelf(visibleRegion);
1750
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 // subtract the opaque region covered by the layers above us
1752 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001753
1754 // compute this layer's dirty region
1755 if (layer->contentDirty) {
1756 // we need to invalidate the whole region
1757 dirty = visibleRegion;
1758 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001759 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001760 layer->contentDirty = false;
1761 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001762 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001763 * the exposed region consists of two components:
1764 * 1) what's VISIBLE now and was COVERED before
1765 * 2) what's EXPOSED now less what was EXPOSED before
1766 *
1767 * note that (1) is conservative, we start with the whole
1768 * visible region but only keep what used to be covered by
1769 * something -- which mean it may have been exposed.
1770 *
1771 * (2) handles areas that were not covered by anything but got
1772 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001773 */
Mathias Agopianab028732010-03-16 16:41:46 -07001774 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775 const Region oldVisibleRegion = layer->visibleRegion;
1776 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001777 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1778 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779 }
1780 dirty.subtractSelf(aboveOpaqueLayers);
1781
1782 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001783 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001784
Mathias Agopianab028732010-03-16 16:41:46 -07001785 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001787
Jesse Halla8026d22012-09-25 13:25:04 -07001788 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001789 layer->setVisibleRegion(visibleRegion);
1790 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001791 layer->setVisibleNonTransparentRegion(
1792 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001793 }
1794
Mathias Agopian87baae12012-07-31 12:38:26 -07001795 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001796}
1797
Mathias Agopian87baae12012-07-31 12:38:26 -07001798void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1799 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001800 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001801 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1802 if (hw->getLayerStack() == layerStack) {
1803 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001804 }
1805 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001806}
1807
Dan Stoza6b9454d2014-11-07 16:00:59 -08001808bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001809{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810 ALOGV("handlePageFlip");
1811
Mathias Agopian4fec8732012-06-29 14:12:52 -07001812 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001813
Mathias Agopian4fec8732012-06-29 14:12:52 -07001814 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001815 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001817
1818 // Store the set of layers that need updates. This set must not change as
1819 // buffers are being latched, as this could result in a deadlock.
1820 // Example: Two producers share the same command stream and:
1821 // 1.) Layer 0 is latched
1822 // 2.) Layer 0 gets a new frame
1823 // 2.) Layer 1 gets a new frame
1824 // 3.) Layer 1 is latched.
1825 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1826 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001827 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001828 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001829 if (layer->hasQueuedFrame()) {
1830 frameQueued = true;
1831 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001833 } else {
1834 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001835 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001836 } else {
1837 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001838 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001839 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001840 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001841 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001842 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001843 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001844 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001845 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001846
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001847 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001848
1849 // If we will need to wake up at some time in the future to deal with a
1850 // queued frame that shouldn't be displayed during this vsync period, wake
1851 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001853 signalLayerUpdate();
1854 }
1855
1856 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001857 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001858}
1859
Mathias Agopianad456f92011-01-13 17:53:01 -08001860void SurfaceFlinger::invalidateHwcGeometry()
1861{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001863}
1864
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001865
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001867 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001868{
Dan Stoza71433162014-02-04 16:22:36 -08001869 // We only need to actually compose the display if:
1870 // 1) It is being handled by hardware composer, which may need this to
1871 // keep its virtual display state machine in sync, or
1872 // 2) There is work to be done (the dirty region isn't empty)
1873 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1874 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001876 return;
1877 }
1878
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 ALOGV("doDisplayComposition");
1880
Mathias Agopian87baae12012-07-31 12:38:26 -07001881 Region dirtyRegion(inDirtyRegion);
1882
Mathias Agopianb8a55602009-06-26 19:06:36 -07001883 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001884 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885
Mathias Agopian42977342012-08-05 00:40:46 -07001886 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001887 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001888 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1889 // takes a rectangle, we must make sure to update that whole
1890 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001891 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001892 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001893 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001894 // We need to redraw the rectangle that will be updated
1895 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001896 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001897 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001898 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001899 } else {
1900 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001901 dirtyRegion.set(hw->bounds());
1902 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001903 }
1904 }
1905
Alan Viverette9c5a3332013-09-12 20:04:35 -07001906 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001907 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001908 } else {
1909 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001910 mat4 colorMatrix = mColorMatrix;
1911 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001912 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001913 }
Dan Stozaf0087992014-10-20 15:46:09 -07001914 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001915 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001916 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001918
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001919 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001920 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001921
1922 // swap buffers (presentation)
1923 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001924}
1925
Dan Stoza9e56aa02015-11-02 13:00:03 -08001926bool SurfaceFlinger::doComposeSurfaces(
1927 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001928{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001929 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001930
Dan Stoza9e56aa02015-11-02 13:00:03 -08001931 const auto hwcId = displayDevice->getHwcDisplayId();
1932 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1933 if (hasClientComposition) {
1934 ALOGV("hasClientComposition");
1935
1936 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001937 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001939 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1940 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1941 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1942 }
1943 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001944 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001945
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001946 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1948 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001949 // when using overlays, we assume a fully transparent framebuffer
1950 // NOTE: we could reduce how much we need to clear, for instance
1951 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001952 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001953 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001955 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001956 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001958
1959 // we remove the scissor part
1960 // we're left with the letterbox region
1961 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001963
1964 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001966
1967 // but limit it to the dirty region
1968 region.andSelf(dirty);
1969
Mathias Agopianb9494d52012-04-18 02:28:45 -07001970 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001971 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001972 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08001973 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001974 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07001975 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07001976
Dan Stoza9e56aa02015-11-02 13:00:03 -08001977 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07001978 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07001979 // scissor on the main display. It should never be needed
1980 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08001981 const Rect& bounds(displayDevice->getBounds());
1982 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001983 if (scissor != bounds) {
1984 // scissor doesn't match the screen's dimensions, so we
1985 // need to clear everything outside of it and enable
1986 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07001987
Mathias Agopianf45c5102012-10-24 16:29:17 -07001988 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 const uint32_t height = displayDevice->getHeight();
1990 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07001991 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07001992 }
1993 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07001994 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001995
Mathias Agopian85d751c2012-08-29 16:59:24 -07001996 /*
1997 * and then, render the layers targeted at the framebuffer
1998 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07001999
Dan Stoza9e56aa02015-11-02 13:00:03 -08002000 ALOGV("Rendering client layers");
2001 const Transform& displayTransform = displayDevice->getTransform();
2002 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002003 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 bool firstLayer = true;
2005 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2006 const Region clip(dirty.intersect(
2007 displayTransform.transform(layer->visibleRegion)));
2008 ALOGV("Layer: %s", layer->getName().string());
2009 ALOGV(" Composition type: %s",
2010 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002011 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 switch (layer->getCompositionType(hwcId)) {
2013 case HWC2::Composition::Cursor:
2014 case HWC2::Composition::Device:
2015 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002016 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2018 layer->isOpaque(state) && (state.alpha == 1.0f)
2019 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002020 // never clear the very first layer since we're
2021 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002024 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002025 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002026 case HWC2::Composition::Client: {
2027 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002028 break;
2029 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002031 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 } else {
2034 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002035 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002037 }
2038 } else {
2039 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002041 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002043 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002044 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002045 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002046 }
2047 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002048
2049 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002051 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052}
2053
Mathias Agopian3f844832013-08-07 21:24:32 -07002054void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002055 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002056 RenderEngine& engine(getRenderEngine());
2057 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002058}
2059
Dan Stoza7d89d062015-04-30 13:29:25 -07002060status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002061 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002062 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002063 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002064{
Dan Stoza7d89d062015-04-30 13:29:25 -07002065 // add this layer to the current state list
2066 {
2067 Mutex::Autolock _l(mStateLock);
2068 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2069 return NO_MEMORY;
2070 }
2071 mCurrentState.layersSortedByZ.add(lbc);
2072 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2073 }
2074
Mathias Agopian96f08192010-06-02 23:28:45 -07002075 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002076 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002077
Dan Stoza7d89d062015-04-30 13:29:25 -07002078 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002079}
2080
Mathias Agopian3f844832013-08-07 21:24:32 -07002081status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002083 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002084 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002085 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002086 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002087 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002088 return NO_ERROR;
2089 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002090 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091}
2092
Dan Stozac7014012014-02-14 15:03:43 -08002093uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002094 return android_atomic_release_load(&mTransactionFlags);
2095}
2096
Mathias Agopian3f844832013-08-07 21:24:32 -07002097uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2099}
2100
Mathias Agopian3f844832013-08-07 21:24:32 -07002101uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002102 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2103 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002104 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002105 }
2106 return old;
2107}
2108
Mathias Agopian8b33f032012-07-24 20:43:54 -07002109void SurfaceFlinger::setTransactionState(
2110 const Vector<ComposerState>& state,
2111 const Vector<DisplayState>& displays,
2112 uint32_t flags)
2113{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002114 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002115 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002116 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002118 if (flags & eAnimation) {
2119 // For window updates that are part of an animation we must wait for
2120 // previous animation "frames" to be handled.
2121 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002122 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002123 if (CC_UNLIKELY(err != NO_ERROR)) {
2124 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002125 // caller after a few seconds.
2126 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2127 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002128 mAnimTransactionPending = false;
2129 break;
2130 }
2131 }
2132 }
2133
Mathias Agopiane57f2922012-08-09 16:29:12 -07002134 size_t count = displays.size();
2135 for (size_t i=0 ; i<count ; i++) {
2136 const DisplayState& s(displays[i]);
2137 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002138 }
2139
Mathias Agopiane57f2922012-08-09 16:29:12 -07002140 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002141 for (size_t i=0 ; i<count ; i++) {
2142 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002143 // Here we need to check that the interface we're given is indeed
2144 // one of our own. A malicious client could give us a NULL
2145 // IInterface, or one of its own or even one of our own but a
2146 // different type. All these situations would cause us to crash.
2147 //
2148 // NOTE: it would be better to use RTTI as we could directly check
2149 // that we have a Client*. however, RTTI is disabled in Android.
2150 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002151 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002152 if (binder != NULL) {
2153 String16 desc(binder->getInterfaceDescriptor());
2154 if (desc == ISurfaceComposerClient::descriptor) {
2155 sp<Client> client( static_cast<Client *>(s.client.get()) );
2156 transactionFlags |= setClientStateLocked(client, s.state);
2157 }
2158 }
2159 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002160 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002161
Mathias Agopian386aa982011-11-07 21:58:03 -08002162 if (transactionFlags) {
2163 // this triggers the transaction
2164 setTransactionFlags(transactionFlags);
2165
2166 // if this is a synchronous transaction, wait for it to take effect
2167 // before returning.
2168 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002169 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002170 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002171 if (flags & eAnimation) {
2172 mAnimTransactionPending = true;
2173 }
2174 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002175 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2176 if (CC_UNLIKELY(err != NO_ERROR)) {
2177 // just in case something goes wrong in SF, return to the
2178 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002179 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2180 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002181 break;
2182 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002183 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002184 }
2185}
2186
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2188{
Jesse Hall9a143922012-10-04 16:29:19 -07002189 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2190 if (dpyIdx < 0)
2191 return 0;
2192
Mathias Agopiane57f2922012-08-09 16:29:12 -07002193 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002194 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002195 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002196 const uint32_t what = s.what;
2197 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002198 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002199 disp.surface = s.surface;
2200 flags |= eDisplayTransactionNeeded;
2201 }
2202 }
2203 if (what & DisplayState::eLayerStackChanged) {
2204 if (disp.layerStack != s.layerStack) {
2205 disp.layerStack = s.layerStack;
2206 flags |= eDisplayTransactionNeeded;
2207 }
2208 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002209 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002210 if (disp.orientation != s.orientation) {
2211 disp.orientation = s.orientation;
2212 flags |= eDisplayTransactionNeeded;
2213 }
2214 if (disp.frame != s.frame) {
2215 disp.frame = s.frame;
2216 flags |= eDisplayTransactionNeeded;
2217 }
2218 if (disp.viewport != s.viewport) {
2219 disp.viewport = s.viewport;
2220 flags |= eDisplayTransactionNeeded;
2221 }
2222 }
Michael Lentine47e45402014-07-18 15:34:25 -07002223 if (what & DisplayState::eDisplaySizeChanged) {
2224 if (disp.width != s.width) {
2225 disp.width = s.width;
2226 flags |= eDisplayTransactionNeeded;
2227 }
2228 if (disp.height != s.height) {
2229 disp.height = s.height;
2230 flags |= eDisplayTransactionNeeded;
2231 }
2232 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002233 }
2234 return flags;
2235}
2236
2237uint32_t SurfaceFlinger::setClientStateLocked(
2238 const sp<Client>& client,
2239 const layer_state_t& s)
2240{
2241 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002242 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 if (layer != 0) {
2244 const uint32_t what = s.what;
2245 if (what & layer_state_t::ePositionChanged) {
2246 if (layer->setPosition(s.x, s.y))
2247 flags |= eTraversalNeeded;
2248 }
2249 if (what & layer_state_t::eLayerChanged) {
2250 // NOTE: index needs to be calculated before we update the state
2251 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002252 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002253 mCurrentState.layersSortedByZ.removeAt(idx);
2254 mCurrentState.layersSortedByZ.add(layer);
2255 // we need traversal (state changed)
2256 // AND transaction (list changed)
2257 flags |= eTransactionNeeded|eTraversalNeeded;
2258 }
2259 }
2260 if (what & layer_state_t::eSizeChanged) {
2261 if (layer->setSize(s.w, s.h)) {
2262 flags |= eTraversalNeeded;
2263 }
2264 }
2265 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002266 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002267 flags |= eTraversalNeeded;
2268 }
2269 if (what & layer_state_t::eMatrixChanged) {
2270 if (layer->setMatrix(s.matrix))
2271 flags |= eTraversalNeeded;
2272 }
2273 if (what & layer_state_t::eTransparentRegionChanged) {
2274 if (layer->setTransparentRegionHint(s.transparentRegion))
2275 flags |= eTraversalNeeded;
2276 }
Dan Stoza23116082015-06-18 14:58:39 -07002277 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002278 if (layer->setFlags(s.flags, s.mask))
2279 flags |= eTraversalNeeded;
2280 }
2281 if (what & layer_state_t::eCropChanged) {
2282 if (layer->setCrop(s.crop))
2283 flags |= eTraversalNeeded;
2284 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002285 if (what & layer_state_t::eFinalCropChanged) {
2286 if (layer->setFinalCrop(s.finalCrop))
2287 flags |= eTraversalNeeded;
2288 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002289 if (what & layer_state_t::eLayerStackChanged) {
2290 // NOTE: index needs to be calculated before we update the state
2291 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002292 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002293 mCurrentState.layersSortedByZ.removeAt(idx);
2294 mCurrentState.layersSortedByZ.add(layer);
2295 // we need traversal (state changed)
2296 // AND transaction (list changed)
2297 flags |= eTransactionNeeded|eTraversalNeeded;
2298 }
2299 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002300 if (what & layer_state_t::eDeferTransaction) {
2301 layer->deferTransactionUntil(s.handle, s.frameNumber);
2302 // We don't trigger a traversal here because if no other state is
2303 // changed, we don't want this to cause any more work
2304 }
Robert Carrc3574f72016-03-24 12:19:32 -07002305 if (what & layer_state_t::eOverrideScalingModeChanged) {
2306 layer->setOverrideScalingMode(s.overrideScalingMode);
2307 // We don't trigger a traversal here because if no other state is
2308 // changed, we don't want this to cause any more work
2309 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002310 }
2311 return flags;
2312}
2313
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002314status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002315 const String8& name,
2316 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002317 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2318 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002320 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002321 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002322 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002323 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002324 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002325 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002326
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002327 status_t result = NO_ERROR;
2328
2329 sp<Layer> layer;
2330
Mathias Agopian3165cc22012-08-08 19:42:09 -07002331 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2332 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002333 result = createNormalLayer(client,
2334 name, w, h, flags, format,
2335 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002337 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002338 result = createDimLayer(client,
2339 name, w, h, flags,
2340 handle, gbp, &layer);
2341 break;
2342 default:
2343 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 break;
2345 }
2346
Dan Stoza7d89d062015-04-30 13:29:25 -07002347 if (result != NO_ERROR) {
2348 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002350
2351 result = addClientLayer(client, *handle, *gbp, layer);
2352 if (result != NO_ERROR) {
2353 return result;
2354 }
2355
2356 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002357 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358}
2359
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002360status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2361 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2362 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363{
2364 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002365 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366 case PIXEL_FORMAT_TRANSPARENT:
2367 case PIXEL_FORMAT_TRANSLUCENT:
2368 format = PIXEL_FORMAT_RGBA_8888;
2369 break;
2370 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002371 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372 break;
2373 }
2374
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002375 *outLayer = new Layer(this, client, name, w, h, flags);
2376 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2377 if (err == NO_ERROR) {
2378 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002379 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002381
2382 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2383 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002384}
2385
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002386status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2387 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2388 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002390 *outLayer = new LayerDim(this, client, name, w, h, flags);
2391 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002392 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002393 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002394}
2395
Mathias Agopianac9fa422013-02-11 16:40:36 -08002396status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397{
Mathias Agopian67106042013-03-14 19:18:13 -07002398 // called by the window manager when it wants to remove a Layer
2399 status_t err = NO_ERROR;
2400 sp<Layer> l(client->getLayerUser(handle));
2401 if (l != NULL) {
2402 err = removeLayer(l);
2403 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2404 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002405 }
2406 return err;
2407}
2408
Mathias Agopian13127d82013-03-05 17:47:11 -08002409status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002410{
Mathias Agopian67106042013-03-14 19:18:13 -07002411 // called by ~LayerCleaner() when all references to the IBinder (handle)
2412 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002413 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002414 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002415 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002416 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002417 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002418 "error removing layer=%p (%s)", l.get(), strerror(-err));
2419 }
2420 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421}
2422
Mathias Agopianb60314a2012-04-10 22:09:54 -07002423// ---------------------------------------------------------------------------
2424
Andy McFadden13a082e2012-08-24 10:16:42 -07002425void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002426 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002427 Vector<ComposerState> state;
2428 Vector<DisplayState> displays;
2429 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002430 d.what = DisplayState::eDisplayProjectionChanged |
2431 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002432 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002433 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002434 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002435 d.frame.makeInvalid();
2436 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002437 d.width = 0;
2438 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002439 displays.add(d);
2440 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002441 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002442
Dan Stoza9e56aa02015-11-02 13:00:03 -08002443 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2444 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002445 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002446}
2447
2448void SurfaceFlinger::initializeDisplays() {
2449 class MessageScreenInitialized : public MessageBase {
2450 SurfaceFlinger* flinger;
2451 public:
2452 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2453 virtual bool handler() {
2454 flinger->onInitializeDisplays();
2455 return true;
2456 }
2457 };
2458 sp<MessageBase> msg = new MessageScreenInitialized(this);
2459 postMessageAsync(msg); // we may be called from main thread, use async message
2460}
2461
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002462void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2463 int mode) {
2464 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2465 this);
2466 int32_t type = hw->getDisplayType();
2467 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002468
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002469 if (mode == currentMode) {
2470 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002471 return;
2472 }
2473
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002474 hw->setPowerMode(mode);
2475 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2476 ALOGW("Trying to set power mode for virtual display");
2477 return;
2478 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002479
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002480 if (currentMode == HWC_POWER_MODE_OFF) {
2481 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002482 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2483 // FIXME: eventthread only knows about the main display right now
2484 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002485 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002486 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002488 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002489 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002490 repaintEverything();
2491 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002492 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002493 disableHardwareVsync(true); // also cancels any in-progress resync
2494
Mathias Agopiancde87a32012-09-13 14:09:01 -07002495 // FIXME: eventthread only knows about the main display right now
2496 mEventThread->onScreenReleased();
2497 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002498
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002499 getHwComposer().setPowerMode(type, mode);
2500 mVisibleRegionsDirty = true;
2501 // from this point on, SF will stop drawing on this display
2502 } else {
2503 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002504 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002505}
2506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002507void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2508 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002509 SurfaceFlinger& mFlinger;
2510 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002511 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002512 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002513 MessageSetPowerMode(SurfaceFlinger& flinger,
2514 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2515 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002516 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002517 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002518 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002519 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002520 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002521 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002522 ALOGW("Attempt to set power mode = %d for virtual display",
2523 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002524 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002525 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002526 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002527 return true;
2528 }
2529 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002530 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002531 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002532}
2533
2534// ---------------------------------------------------------------------------
2535
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2537{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002539
Mathias Agopianbd115332013-04-18 16:41:04 -07002540 IPCThreadState* ipc = IPCThreadState::self();
2541 const int pid = ipc->getCallingPid();
2542 const int uid = ipc->getCallingUid();
2543 if ((uid != AID_SHELL) &&
2544 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002545 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002546 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002548 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002549 // (this would indicate SF is stuck, but we want to be able to
2550 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002551 status_t err = mStateLock.timedLock(s2ns(1));
2552 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002553 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002554 result.appendFormat(
2555 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2556 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002557 }
2558
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002559 bool dumpAll = true;
2560 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002561 size_t numArgs = args.size();
2562 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002563 if ((index < numArgs) &&
2564 (args[index] == String16("--list"))) {
2565 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002566 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002567 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002568 }
2569
2570 if ((index < numArgs) &&
2571 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002572 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002573 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002574 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002575 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002576
2577 if ((index < numArgs) &&
2578 (args[index] == String16("--latency-clear"))) {
2579 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002580 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002581 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002582 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002583
2584 if ((index < numArgs) &&
2585 (args[index] == String16("--dispsync"))) {
2586 index++;
2587 mPrimaryDispSync.dump(result);
2588 dumpAll = false;
2589 }
Dan Stozab90cf072015-03-05 11:05:59 -08002590
2591 if ((index < numArgs) &&
2592 (args[index] == String16("--static-screen"))) {
2593 index++;
2594 dumpStaticScreenStats(result);
2595 dumpAll = false;
2596 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002597
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002598#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002599 if ((index < numArgs) &&
2600 (args[index] == String16("--fences"))) {
2601 index++;
2602 mFenceTracker.dump(&result);
2603 dumpAll = false;
2604 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002605#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002606 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002607
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002608 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002609 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002610 }
2611
Mathias Agopian9795c422009-08-26 16:36:26 -07002612 if (locked) {
2613 mStateLock.unlock();
2614 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002615 }
2616 write(fd, result.string(), result.size());
2617 return NO_ERROR;
2618}
2619
Dan Stozac7014012014-02-14 15:03:43 -08002620void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2621 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002622{
2623 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2624 const size_t count = currentLayers.size();
2625 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002626 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002627 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002628 }
2629}
2630
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002631void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002632 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002633{
2634 String8 name;
2635 if (index < args.size()) {
2636 name = String8(args[index]);
2637 index++;
2638 }
2639
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2641 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002642 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002643
2644 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002645 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002646 } else {
2647 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2648 const size_t count = currentLayers.size();
2649 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002650 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002651 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002652 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002653 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002654 }
2655 }
2656}
2657
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002658void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002659 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002660{
2661 String8 name;
2662 if (index < args.size()) {
2663 name = String8(args[index]);
2664 index++;
2665 }
2666
2667 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2668 const size_t count = currentLayers.size();
2669 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002670 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002671 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002672 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002673 }
2674 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002675
Svetoslavd85084b2014-03-20 10:28:31 -07002676 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002677}
2678
Jamie Gennis6547ff42013-07-16 20:12:42 -07002679// This should only be called from the main thread. Otherwise it would need
2680// the lock and should use mCurrentState rather than mDrawingState.
2681void SurfaceFlinger::logFrameStats() {
2682 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2683 const size_t count = drawingLayers.size();
2684 for (size_t i=0 ; i<count ; i++) {
2685 const sp<Layer>& layer(drawingLayers[i]);
2686 layer->logFrameStats();
2687 }
2688
2689 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2690}
2691
Andy McFadden4803b742012-09-24 19:07:20 -07002692/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2693{
2694 static const char* config =
2695 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002696#ifdef HAS_CONTEXT_PRIORITY
2697 " HAS_CONTEXT_PRIORITY"
2698#endif
2699#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2700 " NEVER_DEFAULT_TO_ASYNC_MODE"
2701#endif
2702#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2703 " TARGET_DISABLE_TRIPLE_BUFFERING"
2704#endif
2705 "]";
2706 result.append(config);
2707}
2708
Dan Stozab90cf072015-03-05 11:05:59 -08002709void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2710{
2711 result.appendFormat("Static screen stats:\n");
2712 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2713 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2714 float percent = 100.0f *
2715 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2716 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2717 b + 1, bucketTimeSec, percent);
2718 }
2719 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2720 float percent = 100.0f *
2721 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2722 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2723 NUM_BUCKETS - 1, bucketTimeSec, percent);
2724}
2725
Mathias Agopian74d211a2013-04-22 16:55:35 +02002726void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2727 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002728{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002729 bool colorize = false;
2730 if (index < args.size()
2731 && (args[index] == String16("--color"))) {
2732 colorize = true;
2733 index++;
2734 }
2735
2736 Colorizer colorizer(colorize);
2737
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002738 // figure out if we're stuck somewhere
2739 const nsecs_t now = systemTime();
2740 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2741 const nsecs_t inTransaction(mDebugInTransaction);
2742 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2743 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2744
2745 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002746 * Dump library configuration.
2747 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002748
2749 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002750 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002751 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002752 appendSfConfigString(result);
2753 appendUiConfigString(result);
2754 appendGuiConfigString(result);
2755 result.append("\n");
2756
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002757 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002758 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002759 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002760 result.append(SyncFeatures::getInstance().toString());
2761 result.append("\n");
2762
Dan Stoza9e56aa02015-11-02 13:00:03 -08002763 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2764
Andy McFadden41d67d72014-04-25 16:58:34 -07002765 colorizer.bold(result);
2766 result.append("DispSync configuration: ");
2767 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002768 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2769 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002770 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2771 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002772 result.append("\n");
2773
Dan Stozab90cf072015-03-05 11:05:59 -08002774 // Dump static screen stats
2775 result.append("\n");
2776 dumpStaticScreenStats(result);
2777 result.append("\n");
2778
Andy McFadden4803b742012-09-24 19:07:20 -07002779 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002780 * Dump the visible layer list
2781 */
2782 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2783 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002784 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002785 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002786 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002787 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002788 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002789 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002790 }
2791
2792 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002793 * Dump Display state
2794 */
2795
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002796 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002797 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002798 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002799 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2800 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002801 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002802 }
2803
2804 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002805 * Dump SurfaceFlinger global state
2806 */
2807
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002808 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002809 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002810 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002811
Mathias Agopian888c8222012-08-04 21:10:38 -07002812 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002813 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002814
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002815 colorizer.bold(result);
2816 result.appendFormat("EGL implementation : %s\n",
2817 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2818 colorizer.reset(result);
2819 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002820 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002821
Mathias Agopian875d8e12013-06-07 15:35:48 -07002822 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002823
Mathias Agopian42977342012-08-05 00:40:46 -07002824 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002825 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2826 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002827 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002828 " last eglSwapBuffers() time: %f us\n"
2829 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002830 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002831 " refresh-rate : %f fps\n"
2832 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002833 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002834 " gpu_to_cpu_unsupported : %d\n"
2835 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002836 mLastSwapBufferTime/1000.0,
2837 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002838 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 1e9 / activeConfig->getVsyncPeriod(),
2840 activeConfig->getDpiX(),
2841 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002842 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002843
Mathias Agopian74d211a2013-04-22 16:55:35 +02002844 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002845 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002846
Mathias Agopian74d211a2013-04-22 16:55:35 +02002847 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002848 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002849
2850 /*
2851 * VSYNC state
2852 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002853 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002854
2855 /*
2856 * Dump HWComposer state
2857 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002858 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002859 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002860 colorizer.reset(result);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2862 mHasColorMatrix;
2863 result.appendFormat(" h/w composer %s\n",
2864 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002865 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002866
2867 /*
2868 * Dump gralloc state
2869 */
2870 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2871 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002872}
2873
Mathias Agopian13127d82013-03-05 17:47:11 -08002874const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002875SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002876 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002877 wp<IBinder> dpy;
2878 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2879 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2880 dpy = mDisplays.keyAt(i);
2881 break;
2882 }
2883 }
2884 if (dpy == NULL) {
2885 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2886 // Just use the primary display so we have something to return
2887 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2888 }
2889 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002890}
2891
Keun young Park63f165f2012-08-31 10:53:36 -07002892bool SurfaceFlinger::startDdmConnection()
2893{
2894 void* libddmconnection_dso =
2895 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2896 if (!libddmconnection_dso) {
2897 return false;
2898 }
2899 void (*DdmConnection_start)(const char* name);
2900 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002901 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002902 if (!DdmConnection_start) {
2903 dlclose(libddmconnection_dso);
2904 return false;
2905 }
2906 (*DdmConnection_start)(getServiceName());
2907 return true;
2908}
2909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910status_t SurfaceFlinger::onTransact(
2911 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2912{
2913 switch (code) {
2914 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002915 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002916 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002918 case CLEAR_ANIMATION_FRAME_STATS:
2919 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002920 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002921 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922 {
2923 // codes that require permission check
2924 IPCThreadState* ipc = IPCThreadState::self();
2925 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002926 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002927 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002928 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002929 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002930 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2931 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002933 break;
2934 }
2935 case CAPTURE_SCREEN:
2936 {
2937 // codes that require permission check
2938 IPCThreadState* ipc = IPCThreadState::self();
2939 const int pid = ipc->getCallingPid();
2940 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002941 if ((uid != AID_GRAPHICS) &&
2942 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002943 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002944 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2945 return PERMISSION_DENIED;
2946 }
2947 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 }
2949 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002950
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2952 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002953 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002954 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002955 IPCThreadState* ipc = IPCThreadState::self();
2956 const int pid = ipc->getCallingPid();
2957 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002958 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002959 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 return PERMISSION_DENIED;
2961 }
2962 int n;
2963 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07002964 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07002965 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 return NO_ERROR;
2967 case 1002: // SHOW_UPDATES
2968 n = data.readInt32();
2969 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07002970 invalidateHwcGeometry();
2971 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002972 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07002974 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002975 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002977 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07002978 setTransactionFlags(
2979 eTransactionNeeded|
2980 eDisplayTransactionNeeded|
2981 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002982 return NO_ERROR;
2983 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08002984 case 1006:{ // send empty update
2985 signalRefresh();
2986 return NO_ERROR;
2987 }
Mathias Agopian53331da2011-08-22 21:44:41 -07002988 case 1008: // toggle use of hw composer
2989 n = data.readInt32();
2990 mDebugDisableHWC = n ? 1 : 0;
2991 invalidateHwcGeometry();
2992 repaintEverything();
2993 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07002994 case 1009: // toggle use of transform hint
2995 n = data.readInt32();
2996 mDebugDisableTransformHint = n ? 1 : 0;
2997 invalidateHwcGeometry();
2998 repaintEverything();
2999 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003001 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002 reply->writeInt32(0);
3003 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003004 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003005 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006 return NO_ERROR;
3007 case 1013: {
3008 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003009 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3010 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003011 return NO_ERROR;
3012 }
3013 case 1014: {
3014 // daltonize
3015 n = data.readInt32();
3016 switch (n % 10) {
3017 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3018 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3019 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3020 }
3021 if (n >= 10) {
3022 mDaltonizer.setMode(Daltonizer::correction);
3023 } else {
3024 mDaltonizer.setMode(Daltonizer::simulation);
3025 }
3026 mDaltonize = n > 0;
3027 invalidateHwcGeometry();
3028 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003029 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003031 case 1015: {
3032 // apply a color matrix
3033 n = data.readInt32();
3034 mHasColorMatrix = n ? 1 : 0;
3035 if (n) {
3036 // color matrix is sent as mat3 matrix followed by vec3
3037 // offset, then packed into a mat4 where the last row is
3038 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003039 for (size_t i = 0 ; i < 4; i++) {
3040 for (size_t j = 0; j < 4; j++) {
3041 mColorMatrix[i][j] = data.readFloat();
3042 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003043 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003044 } else {
3045 mColorMatrix = mat4();
3046 }
3047 invalidateHwcGeometry();
3048 repaintEverything();
3049 return NO_ERROR;
3050 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003051 // This is an experimental interface
3052 // Needs to be shifted to proper binder interface when we productize
3053 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003054 n = data.readInt32();
3055 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003056 return NO_ERROR;
3057 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003058 case 1017: {
3059 n = data.readInt32();
3060 mForceFullDamage = static_cast<bool>(n);
3061 return NO_ERROR;
3062 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003063 case 1018: { // Modify Choreographer's phase offset
3064 n = data.readInt32();
3065 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3066 return NO_ERROR;
3067 }
3068 case 1019: { // Modify SurfaceFlinger's phase offset
3069 n = data.readInt32();
3070 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3071 return NO_ERROR;
3072 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073 }
3074 }
3075 return err;
3076}
3077
Mathias Agopian53331da2011-08-22 21:44:41 -07003078void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003079 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003080 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003081}
3082
Mathias Agopian59119e62010-10-11 12:37:43 -07003083// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003084// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003085// ---------------------------------------------------------------------------
3086
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003087/* The code below is here to handle b/8734824
3088 *
3089 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003090 * from the surfaceflinger thread to the calling binder thread, where they
3091 * are executed. This allows the calling thread in the calling process to be
3092 * reused and not depend on having "enough" binder threads to handle the
3093 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003094 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003095class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003096 /* Parts of GraphicProducerWrapper are run on two different threads,
3097 * communicating by sending messages via Looper but also by shared member
3098 * data. Coherence maintenance is subtle and in places implicit (ugh).
3099 *
3100 * Don't rely on Looper's sendMessage/handleMessage providing
3101 * release/acquire semantics for any data not actually in the Message.
3102 * Data going from surfaceflinger to binder threads needs to be
3103 * synchronized explicitly.
3104 *
3105 * Barrier open/wait do provide release/acquire semantics. This provides
3106 * implicit synchronization for data coming back from binder to
3107 * surfaceflinger threads.
3108 */
3109
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003110 sp<IGraphicBufferProducer> impl;
3111 sp<Looper> looper;
3112 status_t result;
3113 bool exitPending;
3114 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003115 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003116 uint32_t code;
3117 Parcel const* data;
3118 Parcel* reply;
3119
3120 enum {
3121 MSG_API_CALL,
3122 MSG_EXIT
3123 };
3124
3125 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003126 * Called on surfaceflinger thread. This is called by our "fake"
3127 * BpGraphicBufferProducer. We package the data and reply Parcel and
3128 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003129 */
3130 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003131 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003132 this->code = code;
3133 this->data = &data;
3134 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003135 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003136 // if we've exited, we run the message synchronously right here.
3137 // note (JH): as far as I can tell from looking at the code, this
3138 // never actually happens. if it does, i'm not sure if it happens
3139 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003140 handleMessage(Message(MSG_API_CALL));
3141 } else {
3142 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003143 // Prevent stores to this->{code, data, reply} from being
3144 // reordered later than the construction of Message.
3145 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003146 looper->sendMessage(this, Message(MSG_API_CALL));
3147 barrier.wait();
3148 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003149 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003150 }
3151
3152 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003153 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003154 * call the real BpGraphicBufferProducer.
3155 */
3156 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003157 int what = message.what;
3158 // Prevent reads below from happening before the read from Message
3159 atomic_thread_fence(memory_order_acquire);
3160 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003161 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003162 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003163 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003164 exitRequested = true;
3165 }
3166 }
3167
3168public:
Jesse Hallb154c422014-07-13 12:47:02 -07003169 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3170 : impl(impl),
3171 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003172 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003173 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003174 exitRequested(false),
3175 code(0),
3176 data(NULL),
3177 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003178 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003179
Jesse Hallb154c422014-07-13 12:47:02 -07003180 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003181 status_t waitForResponse() {
3182 do {
3183 looper->pollOnce(-1);
3184 } while (!exitRequested);
3185 return result;
3186 }
3187
Jesse Hallb154c422014-07-13 12:47:02 -07003188 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003189 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003190 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003191 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003192 // Ensure this->result is visible to the binder thread before it
3193 // handles the message.
3194 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003195 looper->sendMessage(this, Message(MSG_EXIT));
3196 }
3197};
3198
3199
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003200status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3201 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003202 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003203 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003204 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003205
3206 if (CC_UNLIKELY(display == 0))
3207 return BAD_VALUE;
3208
3209 if (CC_UNLIKELY(producer == 0))
3210 return BAD_VALUE;
3211
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003212 // if we have secure windows on this display, never allow the screen capture
3213 // unless the producer interface is local (i.e.: we can take a screenshot for
3214 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003215 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003216
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003217 // Convert to surfaceflinger's internal rotation type.
3218 Transform::orientation_flags rotationFlags;
3219 switch (rotation) {
3220 case ISurfaceComposer::eRotateNone:
3221 rotationFlags = Transform::ROT_0;
3222 break;
3223 case ISurfaceComposer::eRotate90:
3224 rotationFlags = Transform::ROT_90;
3225 break;
3226 case ISurfaceComposer::eRotate180:
3227 rotationFlags = Transform::ROT_180;
3228 break;
3229 case ISurfaceComposer::eRotate270:
3230 rotationFlags = Transform::ROT_270;
3231 break;
3232 default:
3233 rotationFlags = Transform::ROT_0;
3234 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3235 break;
3236 }
3237
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003238 class MessageCaptureScreen : public MessageBase {
3239 SurfaceFlinger* flinger;
3240 sp<IBinder> display;
3241 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003242 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003243 uint32_t reqWidth, reqHeight;
3244 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003245 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003246 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003247 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003248 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003249 public:
3250 MessageCaptureScreen(SurfaceFlinger* flinger,
3251 const sp<IBinder>& display,
3252 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003253 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003254 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003255 bool useIdentityTransform,
3256 Transform::orientation_flags rotation,
3257 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003258 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003259 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003260 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003261 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003262 rotation(rotation), result(PERMISSION_DENIED),
3263 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003264 {
3265 }
3266 status_t getResult() const {
3267 return result;
3268 }
3269 virtual bool handler() {
3270 Mutex::Autolock _l(flinger->mStateLock);
3271 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003272 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003273 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003274 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003275 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003276 return true;
3277 }
3278 };
3279
Mathias Agopian9eb1f052013-04-10 16:27:17 -07003280 // make sure to process transactions before screenshots -- a transaction
3281 // might already be pending but scheduled for VSYNC; this guarantees we
3282 // will handle it before the screenshot. When VSYNC finally arrives
3283 // the scheduled transaction will be a no-op. If no transactions are
3284 // scheduled at this time, this will end-up being a no-op as well.
3285 mEventQueue.invalidateTransactionNow();
3286
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003287 // this creates a "fake" BBinder which will serve as a "fake" remote
3288 // binder to receive the marshaled calls and forward them to the
3289 // real remote (a BpGraphicBufferProducer)
3290 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3291
3292 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3293 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003294 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003295 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003296 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003297 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003298
3299 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003300 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003301 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003302 }
3303 return res;
3304}
3305
Mathias Agopian180f10d2013-04-10 22:55:41 -07003306
3307void SurfaceFlinger::renderScreenImplLocked(
3308 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003309 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003310 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003311 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003312{
3313 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003314 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003315
3316 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003317 const int32_t hw_w = hw->getWidth();
3318 const int32_t hw_h = hw->getHeight();
3319 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003320 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003321
Dan Stozac1879002014-05-22 15:59:05 -07003322 // if a default or invalid sourceCrop is passed in, set reasonable values
3323 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3324 !sourceCrop.isValid()) {
3325 sourceCrop.setLeftTop(Point(0, 0));
3326 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3327 }
3328
3329 // ensure that sourceCrop is inside screen
3330 if (sourceCrop.left < 0) {
3331 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3332 }
Dan Stozabe31f442014-06-11 11:20:54 -07003333 if (sourceCrop.right > hw_w) {
3334 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003335 }
3336 if (sourceCrop.top < 0) {
3337 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3338 }
Dan Stozabe31f442014-06-11 11:20:54 -07003339 if (sourceCrop.bottom > hw_h) {
3340 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003341 }
3342
Mathias Agopian180f10d2013-04-10 22:55:41 -07003343 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003344 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003345
3346 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003347 engine.setViewportAndProjection(
3348 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003349 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003350
3351 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003352 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003353
3354 const LayerVector& layers( mDrawingState.layersSortedByZ );
3355 const size_t count = layers.size();
3356 for (size_t i=0 ; i<count ; ++i) {
3357 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003358 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003359 if (state.layerStack == hw->getLayerStack()) {
3360 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3361 if (layer->isVisible()) {
3362 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003363 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003364 if (filtering) layer->setFiltering(false);
3365 }
3366 }
3367 }
3368 }
3369
Mathias Agopian931bda12013-08-28 18:11:46 -07003370 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003371}
3372
3373
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003374status_t SurfaceFlinger::captureScreenImplLocked(
3375 const sp<const DisplayDevice>& hw,
3376 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003377 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003378 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003379 bool useIdentityTransform, Transform::orientation_flags rotation,
3380 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003381{
3382 ATRACE_CALL();
3383
Mathias Agopian180f10d2013-04-10 22:55:41 -07003384 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003385 uint32_t hw_w = hw->getWidth();
3386 uint32_t hw_h = hw->getHeight();
3387
3388 if (rotation & Transform::ROT_90) {
3389 std::swap(hw_w, hw_h);
3390 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003391
Mathias Agopian180f10d2013-04-10 22:55:41 -07003392 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3393 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3394 reqWidth, reqHeight, hw_w, hw_h);
3395 return BAD_VALUE;
3396 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003397
Mathias Agopian180f10d2013-04-10 22:55:41 -07003398 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3399 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3400
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003401 bool secureLayerIsVisible = false;
3402 const LayerVector& layers(mDrawingState.layersSortedByZ);
3403 const size_t count = layers.size();
3404 for (size_t i = 0 ; i < count ; ++i) {
3405 const sp<Layer>& layer(layers[i]);
3406 const Layer::State& state(layer->getDrawingState());
3407 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3408 state.z <= maxLayerZ && layer->isVisible() &&
3409 layer->isSecure()) {
3410 secureLayerIsVisible = true;
3411 }
3412 }
3413
3414 if (!isLocalScreenshot && secureLayerIsVisible) {
3415 ALOGW("FB is protected: PERMISSION_DENIED");
3416 return PERMISSION_DENIED;
3417 }
3418
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003419 // create a surface (because we're a producer, and we need to
3420 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003421 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003422 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003423
Michael Lentine5a16a622015-05-21 13:48:24 -07003424 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3425 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003426 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3427 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003428
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003429 int err = 0;
3430 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003431 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003432 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3433 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003434
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003435 if (err == NO_ERROR) {
3436 ANativeWindowBuffer* buffer;
3437 /* TODO: Once we have the sync framework everywhere this can use
3438 * server-side waits on the fence that dequeueBuffer returns.
3439 */
3440 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3441 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003442 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003443 // create an EGLImage from the buffer so we can later
3444 // turn it into a texture
3445 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3446 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3447 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003448 // this binds the given EGLImage as a framebuffer for the
3449 // duration of this scope.
3450 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3451 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003452 // this will in fact render into our dequeued buffer
3453 // via an FBO, which means we didn't have to create
3454 // an EGLSurface and therefore we're not
3455 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003456 renderScreenImplLocked(
3457 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3458 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003459
Riley Andrews86639902014-08-15 12:27:24 -07003460 // Attempt to create a sync khr object that can produce a sync point. If that
3461 // isn't available, create a non-dupable sync object in the fallback path and
3462 // wait on it directly.
3463 EGLSyncKHR sync;
3464 if (!DEBUG_SCREENSHOTS) {
3465 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003466 // native fence fd will not be populated until flush() is done.
3467 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003468 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003469 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003470 }
Riley Andrews86639902014-08-15 12:27:24 -07003471 if (sync != EGL_NO_SYNC_KHR) {
3472 // get the sync fd
3473 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3474 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3475 ALOGW("captureScreen: failed to dup sync khr object");
3476 syncFd = -1;
3477 }
3478 eglDestroySyncKHR(mEGLDisplay, sync);
3479 } else {
3480 // fallback path
3481 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3482 if (sync != EGL_NO_SYNC_KHR) {
3483 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3484 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3485 EGLint eglErr = eglGetError();
3486 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3487 ALOGW("captureScreen: fence wait timed out");
3488 } else {
3489 ALOGW_IF(eglErr != EGL_SUCCESS,
3490 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3491 }
3492 eglDestroySyncKHR(mEGLDisplay, sync);
3493 } else {
3494 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3495 }
3496 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003497 if (DEBUG_SCREENSHOTS) {
3498 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3499 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3500 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3501 hw, minLayerZ, maxLayerZ);
3502 delete [] pixels;
3503 }
3504
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003505 } else {
3506 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3507 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003508 window->cancelBuffer(window, buffer, syncFd);
3509 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003510 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003511 // destroy our image
3512 eglDestroyImageKHR(mEGLDisplay, image);
3513 } else {
3514 result = BAD_VALUE;
3515 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003516 if (buffer) {
3517 // queueBuffer takes ownership of syncFd
3518 result = window->queueBuffer(window, buffer, syncFd);
3519 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003520 }
3521 } else {
3522 result = BAD_VALUE;
3523 }
3524 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3525 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003526
Mathias Agopian74c40c02010-09-29 13:02:36 -07003527 return result;
3528}
3529
Mathias Agopiand5556842013-09-19 17:08:37 -07003530void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3531 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003532 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003533 for (size_t y=0 ; y<h ; y++) {
3534 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3535 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003536 if (p[x] != 0xFF000000) return;
3537 }
3538 }
3539 ALOGE("*** we just took a black screenshot ***\n"
3540 "requested minz=%d, maxz=%d, layerStack=%d",
3541 minLayerZ, maxLayerZ, hw->getLayerStack());
3542 const LayerVector& layers( mDrawingState.layersSortedByZ );
3543 const size_t count = layers.size();
3544 for (size_t i=0 ; i<count ; ++i) {
3545 const sp<Layer>& layer(layers[i]);
3546 const Layer::State& state(layer->getDrawingState());
3547 const bool visible = (state.layerStack == hw->getLayerStack())
3548 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3549 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003550 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003551 visible ? '+' : '-',
3552 i, layer->getName().string(), state.layerStack, state.z,
3553 layer->isVisible(), state.flags, state.alpha);
3554 }
3555 }
3556}
3557
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003558// ---------------------------------------------------------------------------
3559
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003560SurfaceFlinger::LayerVector::LayerVector() {
3561}
3562
3563SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003564 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003565}
3566
3567int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3568 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003569{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003570 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003571 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3572 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003573
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003574 uint32_t ls = l->getCurrentState().layerStack;
3575 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003576 if (ls != rs)
3577 return ls - rs;
3578
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003579 uint32_t lz = l->getCurrentState().z;
3580 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003581 if (lz != rz)
3582 return lz - rz;
3583
3584 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003585}
3586
3587// ---------------------------------------------------------------------------
3588
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003589SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003590 : type(DisplayDevice::DISPLAY_ID_INVALID),
3591 layerStack(DisplayDevice::NO_LAYER_STACK),
3592 orientation(0),
3593 width(0),
3594 height(0),
3595 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003596}
3597
Pablo Ceballos53390e12015-08-04 11:25:59 -07003598SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3599 DisplayDevice::DisplayType type, bool isSecure)
3600 : type(type),
3601 layerStack(DisplayDevice::NO_LAYER_STACK),
3602 orientation(0),
3603 width(0),
3604 height(0),
3605 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003606 viewport.makeInvalid();
3607 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003608}
3609
3610// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003611
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003612}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003613
3614
3615#if defined(__gl_h_)
3616#error "don't include gl/gl.h in this file"
3617#endif
3618
3619#if defined(__gl2_h_)
3620#error "don't include gl2/gl2.h in this file"
3621#endif