blob: 8baf28c1c9e86c6e6374424a3bdfeddc81fee5a8 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070094
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070095// This is the phase offset in nanoseconds of the software vsync event
96// relative to the vsync event reported by HWComposer. The software vsync
97// event is when SurfaceFlinger and Choreographer-based applications run each
98// frame.
99//
100// This phase offset allows adjustment of the minimum latency from application
101// wake-up (by Choregographer) time to the time at which the resulting window
102// image is displayed. This value may be either positive (after the HW vsync)
103// or negative (before the HW vsync). Setting it to 0 will result in a
104// minimum latency of two vsync periods because the app and SurfaceFlinger
105// will run just after the HW vsync. Setting it to a positive number will
106// result in the minimum latency being:
107//
108// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109//
110// Note that reducing this latency makes it more likely for the applications
111// to not have their window content image ready in time. When this happens
112// the latency will end up being an additional vsync period, and animations
113// will hiccup. Therefore, this latency should be tuned somewhat
114// conservatively (or at least with awareness of the trade-off being made).
115static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700117// This is the phase offset at which SurfaceFlinger's composition runs.
118static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800120// ---------------------------------------------------------------------------
121
Mathias Agopian99b49842011-06-27 16:05:52 -0700122const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125const String16 sDump("android.permission.DUMP");
126
127// ---------------------------------------------------------------------------
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700130 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800131 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700132 mTransactionPending(false),
133 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700134 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700135 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700136 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasColorMatrix(false),
156 mHasPoweredOff(false),
157 mFrameBuckets(),
158 mTotalTime(0),
159 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160{
Steve Blocka19954a2012-01-04 20:05:49 +0000161 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162
163 // debugging stuff...
164 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700165
Mathias Agopianb4b17302013-03-20 18:36:41 -0700166 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700167 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700168
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800169 property_get("debug.sf.showupdates", value, "0");
170 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700171
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700172 property_get("debug.sf.ddms", value, "0");
173 mDebugDDMS = atoi(value);
174 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700175 if (!startDdmConnection()) {
176 // start failed, and DDMS debugging not enabled
177 mDebugDDMS = 0;
178 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700180 ALOGI_IF(mDebugRegion, "showupdates enabled");
181 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700182
183 property_get("debug.sf.disable_backpressure", value, "0");
184 mPropagateBackpressure = !atoi(value);
185 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
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
Tim Murray41a38532016-06-22 12:42:10 -0700468 // set EventThread and SFEventThread to SCHED_FIFO for minimum jitter
469 struct sched_param param = {0};
470 param.sched_priority = 1;
471 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
472 ALOGE("Couldn't set SCHED_FIFO for EventThread");
473 }
474
475 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
476 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
477 }
478
479
Dan Stoza9e56aa02015-11-02 13:00:03 -0800480 // Get a RenderEngine for the given display / config (can't fail)
481 mRenderEngine = RenderEngine::create(mEGLDisplay,
482 HAL_PIXEL_FORMAT_RGBA_8888);
483 }
484
485 // Drop the state lock while we initialize the hardware composer. We drop
486 // the lock because on creation, it will call back into SurfaceFlinger to
487 // initialize the primary display.
488 mHwc = new HWComposer(this);
489 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
490
Jesse Hall692c7232012-11-08 15:41:56 -0800491 Mutex::Autolock _l(mStateLock);
492
Mathias Agopian875d8e12013-06-07 15:35:48 -0700493 // retrieve the EGL context that was selected/created
494 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700495
Mathias Agopianda27af92012-09-13 18:17:13 -0700496 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
497 "couldn't create EGLContext");
498
Dan Stoza9e56aa02015-11-02 13:00:03 -0800499 // make the GLContext current so that we can create textures when creating
500 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700501 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
502
Jamie Gennisd1700752013-10-14 12:22:52 -0700503 mEventControlThread = new EventControlThread(this);
504 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
505
Mathias Agopian92a979a2012-08-02 18:32:23 -0700506 // initialize our drawing state
507 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700508
Andy McFadden13a082e2012-08-24 10:16:42 -0700509 // set initial conditions (e.g. unblank default device)
510 initializeDisplays();
511
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700512 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700513 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514
Dan Stoza9e56aa02015-11-02 13:00:03 -0800515 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700516}
517
Mathias Agopiana67e4182012-06-19 17:26:12 -0700518void SurfaceFlinger::startBootAnim() {
519 // start boot animation
520 property_set("service.bootanim.exit", "0");
521 property_set("ctl.start", "bootanim");
522}
523
Mathias Agopian875d8e12013-06-07 15:35:48 -0700524size_t SurfaceFlinger::getMaxTextureSize() const {
525 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700526}
527
Mathias Agopian875d8e12013-06-07 15:35:48 -0700528size_t SurfaceFlinger::getMaxViewportDims() const {
529 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700530}
531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800533
Jamie Gennis582270d2011-08-17 18:19:00 -0700534bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800535 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800536 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800537 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700538 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800539}
540
Dan Stoza7f7da322014-05-02 15:26:25 -0700541status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
542 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700543 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700544 return BAD_VALUE;
545 }
546
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500547 if (!display.get())
548 return NAME_NOT_FOUND;
549
Jesse Hall692c7232012-11-08 15:41:56 -0800550 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700551 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800552 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700553 type = i;
554 break;
555 }
556 }
557
558 if (type < 0) {
559 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700560 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700561
Mathias Agopian8b736f12012-08-13 17:54:26 -0700562 // TODO: Not sure if display density should handled by SF any longer
563 class Density {
564 static int getDensityFromProperty(char const* propName) {
565 char property[PROPERTY_VALUE_MAX];
566 int density = 0;
567 if (property_get(propName, property, NULL) > 0) {
568 density = atoi(property);
569 }
570 return density;
571 }
572 public:
573 static int getEmuDensity() {
574 return getDensityFromProperty("qemu.sf.lcd_density"); }
575 static int getBuildDensity() {
576 return getDensityFromProperty("ro.sf.lcd_density"); }
577 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700578
Dan Stoza7f7da322014-05-02 15:26:25 -0700579 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700580
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700582 DisplayInfo info = DisplayInfo();
583
Dan Stoza9e56aa02015-11-02 13:00:03 -0800584 float xdpi = hwConfig->getDpiX();
585 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700586
587 if (type == DisplayDevice::DISPLAY_PRIMARY) {
588 // The density of the device is provided by a build property
589 float density = Density::getBuildDensity() / 160.0f;
590 if (density == 0) {
591 // the build doesn't provide a density -- this is wrong!
592 // use xdpi instead
593 ALOGE("ro.sf.lcd_density must be defined as a build property");
594 density = xdpi / 160.0f;
595 }
596 if (Density::getEmuDensity()) {
597 // if "qemu.sf.lcd_density" is specified, it overrides everything
598 xdpi = ydpi = density = Density::getEmuDensity();
599 density /= 160.0f;
600 }
601 info.density = density;
602
603 // TODO: this needs to go away (currently needed only by webkit)
604 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
605 info.orientation = hw->getOrientation();
606 } else {
607 // TODO: where should this value come from?
608 static const int TV_DENSITY = 213;
609 info.density = TV_DENSITY / 160.0f;
610 info.orientation = 0;
611 }
612
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 info.w = hwConfig->getWidth();
614 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700615 info.xdpi = xdpi;
616 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700618 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Andy McFadden91b2ca82014-06-13 14:04:23 -0700620 // This is how far in advance a buffer must be queued for
621 // presentation at a given time. If you want a buffer to appear
622 // on the screen at time N, you must submit the buffer before
623 // (N - presentationDeadline).
624 //
625 // Normally it's one full refresh period (to give SF a chance to
626 // latch the buffer), but this can be reduced by configuring a
627 // DispSync offset. Any additional delays introduced by the hardware
628 // composer or panel must be accounted for here.
629 //
630 // We add an additional 1ms to allow for processing time and
631 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800632 info.presentationDeadline = hwConfig->getVsyncPeriod() -
633 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700634
635 // All non-virtual displays are currently considered secure.
636 info.secure = true;
637
Courtney Goeltzenleuchterfad9d8c2016-06-23 11:49:50 -0600638 // DisplayManager expects each color mode to be its own display
639 // info record.
640 std::vector<int32_t> modes = getHwComposer().getColorModes(type);
641
642 if (modes.size() == 0) {
643 info.colorTransform = 0;
644 configs->push_back(info);
645 }
646 for (int32_t mode : modes) {
647 info.colorTransform = mode;
648 configs->push_back(info);
649 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700650 }
651
Dan Stoza7f7da322014-05-02 15:26:25 -0700652 return NO_ERROR;
653}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700654
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800655status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700656 DisplayStatInfo* stats) {
657 if (stats == NULL) {
658 return BAD_VALUE;
659 }
660
661 // FIXME for now we always return stats for the primary display
662 memset(stats, 0, sizeof(*stats));
663 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
664 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
665 return NO_ERROR;
666}
667
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700668int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700669 sp<DisplayDevice> device(getDisplayDevice(display));
670 if (device != NULL) {
671 return device->getActiveConfig();
672 }
673 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700674}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700675
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700676void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
677 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
678 this);
679 int32_t type = hw->getDisplayType();
680 int currentMode = hw->getActiveConfig();
681
682 if (mode == currentMode) {
683 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
684 return;
685 }
686
687 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
688 ALOGW("Trying to set config for virtual display");
689 return;
690 }
691
692 hw->setActiveConfig(mode);
693 getHwComposer().setActiveConfig(type, mode);
694}
695
696status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
697 class MessageSetActiveConfig: public MessageBase {
698 SurfaceFlinger& mFlinger;
699 sp<IBinder> mDisplay;
700 int mMode;
701 public:
702 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
703 int mode) :
704 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
705 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700706 Vector<DisplayInfo> configs;
707 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700708 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700709 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700710 mMode, configs.size());
711 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700712 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
713 if (hw == NULL) {
714 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700715 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700716 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
717 ALOGW("Attempt to set active config = %d for virtual display",
718 mMode);
719 } else {
720 mFlinger.setActiveConfigInternal(hw, mMode);
721 }
722 return true;
723 }
724 };
725 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
726 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700727 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700728}
729
Svetoslavd85084b2014-03-20 10:28:31 -0700730status_t SurfaceFlinger::clearAnimationFrameStats() {
731 Mutex::Autolock _l(mStateLock);
732 mAnimFrameTracker.clearStats();
733 return NO_ERROR;
734}
735
736status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
737 Mutex::Autolock _l(mStateLock);
738 mAnimFrameTracker.getStats(outStats);
739 return NO_ERROR;
740}
741
Dan Stozac4f471e2016-03-24 09:31:08 -0700742status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
743 HdrCapabilities* outCapabilities) const {
744 Mutex::Autolock _l(mStateLock);
745
746 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
747 if (displayDevice == nullptr) {
748 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
749 return BAD_VALUE;
750 }
751
752 std::unique_ptr<HdrCapabilities> capabilities =
753 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
754 if (capabilities) {
755 std::swap(*outCapabilities, *capabilities);
756 } else {
757 return BAD_VALUE;
758 }
759
760 return NO_ERROR;
761}
762
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800763// ----------------------------------------------------------------------------
764
765sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800766 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700767}
768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800770
771void SurfaceFlinger::waitForEvent() {
772 mEventQueue.waitMessage();
773}
774
775void SurfaceFlinger::signalTransaction() {
776 mEventQueue.invalidate();
777}
778
779void SurfaceFlinger::signalLayerUpdate() {
780 mEventQueue.invalidate();
781}
782
783void SurfaceFlinger::signalRefresh() {
784 mEventQueue.refresh();
785}
786
787status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800788 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800789 return mEventQueue.postMessage(msg, reltime);
790}
791
792status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800793 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800794 status_t res = mEventQueue.postMessage(msg, reltime);
795 if (res == NO_ERROR) {
796 msg->wait();
797 }
798 return res;
799}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700801void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700802 do {
803 waitForEvent();
804 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800805}
806
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700807void SurfaceFlinger::enableHardwareVsync() {
808 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700809 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700810 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700811 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
812 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700813 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700814 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700815}
816
Jesse Hall948fe0c2013-10-14 12:56:09 -0700817void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700818 Mutex::Autolock _l(mHWVsyncLock);
819
Jesse Hall948fe0c2013-10-14 12:56:09 -0700820 if (makeAvailable) {
821 mHWVsyncAvailable = true;
822 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700823 // Hardware vsync is not currently available, so abort the resync
824 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700825 return;
826 }
827
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
829 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700830
831 mPrimaryDispSync.reset();
832 mPrimaryDispSync.setPeriod(period);
833
834 if (!mPrimaryHWVsyncEnabled) {
835 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700836 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
837 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700838 mPrimaryHWVsyncEnabled = true;
839 }
840}
841
Jesse Hall948fe0c2013-10-14 12:56:09 -0700842void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700843 Mutex::Autolock _l(mHWVsyncLock);
844 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700845 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
846 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700847 mPrimaryDispSync.endResync();
848 mPrimaryHWVsyncEnabled = false;
849 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700850 if (makeUnavailable) {
851 mHWVsyncAvailable = false;
852 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700853}
854
Tim Murray4a4e4a22016-04-19 16:29:23 +0000855void SurfaceFlinger::resyncWithRateLimit() {
856 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
857 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700858 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000859 }
860}
861
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700863 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700864
Jamie Gennisd1700752013-10-14 12:22:52 -0700865 { // Scope for the lock
866 Mutex::Autolock _l(mHWVsyncLock);
867 if (type == 0 && mPrimaryHWVsyncEnabled) {
868 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700869 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700870 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700871
872 if (needsHwVsync) {
873 enableHardwareVsync();
874 } else {
875 disableHardwareVsync(false);
876 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700877}
878
Dan Stoza9e56aa02015-11-02 13:00:03 -0800879void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
880 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
881 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
882 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700883
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 // All non-virtual displays are currently considered secure.
885 bool isSecure = true;
886
887 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
888 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
889 wp<IBinder> token = mBuiltinDisplays[type];
890
891 sp<IGraphicBufferProducer> producer;
892 sp<IGraphicBufferConsumer> consumer;
893 BufferQueue::createBufferQueue(&producer, &consumer,
894 new GraphicBufferAlloc());
895
896 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
897 DisplayDevice::DISPLAY_PRIMARY, consumer);
898 sp<DisplayDevice> hw = new DisplayDevice(this,
899 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
900 producer, mRenderEngine->getEGLConfig());
901 mDisplays.add(token, hw);
902 } else {
903 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700904 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800905 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800906 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700907 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800908 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
909 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700910 }
911 setTransactionFlags(eDisplayTransactionNeeded);
912
Andy McFadden9e9689c2012-10-10 18:17:51 -0700913 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700914 }
Mathias Agopian86303202012-07-24 22:46:10 -0700915}
916
Dan Stoza9e56aa02015-11-02 13:00:03 -0800917void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700918 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 getHwComposer().setVsyncEnabled(disp,
920 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700921}
922
Mathias Agopian4fec8732012-06-29 14:12:52 -0700923void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800924 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800925 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800926 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -0700927 bool frameMissed = !mHadClientComposition &&
928 mPreviousPresentFence != Fence::NO_FENCE &&
929 mPreviousPresentFence->getSignalTime() == INT64_MAX;
930 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -0700931 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -0700932 signalLayerUpdate();
933 break;
934 }
935
Dan Stoza6b9454d2014-11-07 16:00:59 -0800936 bool refreshNeeded = handleMessageTransaction();
937 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800938 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800939 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800940 // Signal a refresh if a transaction modified the window state,
941 // a new buffer was latched, or if HWC has requested a full
942 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800943 signalRefresh();
944 }
945 break;
946 }
947 case MessageQueue::REFRESH: {
948 handleMessageRefresh();
949 break;
950 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800951 }
952}
953
Dan Stoza6b9454d2014-11-07 16:00:59 -0800954bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700955 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700956 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700957 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800958 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700959 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800960 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700961}
962
Dan Stoza6b9454d2014-11-07 16:00:59 -0800963bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700964 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800965 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700966}
967
968void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700969 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700970
Pablo Ceballos40845df2016-01-25 17:41:15 -0800971 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700972
Dan Stoza05dacfb2016-07-01 13:33:38 -0700973 preComposition();
974 rebuildLayerStacks();
975 setUpHWComposer();
976 doDebugFlashRegions();
977 doComposition();
978 postComposition(refreshStartTime);
979
980 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
981 mHadClientComposition = mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983 // Release any buffers which were replaced this frame
984 for (auto& layer : mLayersWithQueuedFrames) {
985 layer->releasePendingBuffer();
986 }
987 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700988}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700989
Mathias Agopiancd60f992012-08-16 16:28:27 -0700990void SurfaceFlinger::doDebugFlashRegions()
991{
992 // is debugging enabled
993 if (CC_LIKELY(!mDebugRegion))
994 return;
995
996 const bool repaintEverything = mRepaintEverything;
997 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
998 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700999 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001000 // transform the dirty region into this screen's coordinate space
1001 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1002 if (!dirtyRegion.isEmpty()) {
1003 // redraw the whole screen
1004 doComposeSurfaces(hw, Region(hw->bounds()));
1005
1006 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001007 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001008 RenderEngine& engine(getRenderEngine());
1009 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1010
Mathias Agopianda27af92012-09-13 18:17:13 -07001011 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001012 }
1013 }
1014 }
1015
1016 postFramebuffer();
1017
1018 if (mDebugRegion > 1) {
1019 usleep(mDebugRegion * 1000);
1020 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001021
Dan Stoza9e56aa02015-11-02 13:00:03 -08001022 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001023 auto& displayDevice = mDisplays[displayId];
1024 if (!displayDevice->isDisplayOn()) {
1025 continue;
1026 }
1027
1028 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001029 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1030 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001031 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001032}
1033
1034void SurfaceFlinger::preComposition()
1035{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001036 ATRACE_CALL();
1037 ALOGV("preComposition");
1038
Mathias Agopiancd60f992012-08-16 16:28:27 -07001039 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001040 const LayerVector& layers(mDrawingState.layersSortedByZ);
1041 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001042 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001043 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001044 needExtraInvalidate = true;
1045 }
1046 }
1047 if (needExtraInvalidate) {
1048 signalLayerUpdate();
1049 }
1050}
1051
Pablo Ceballos40845df2016-01-25 17:41:15 -08001052void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001053{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001054 ATRACE_CALL();
1055 ALOGV("postComposition");
1056
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001057 const LayerVector& layers(mDrawingState.layersSortedByZ);
1058 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001059 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001060 bool frameLatched = layers[i]->onPostComposition();
1061 if (frameLatched) {
1062 recordBufferingStats(layers[i]->getName().string(),
1063 layers[i]->getOccupancyHistory(false));
1064 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001065 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001066
Dan Stoza9e56aa02015-11-02 13:00:03 -08001067 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001068
1069 if (presentFence->isValid()) {
1070 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1071 enableHardwareVsync();
1072 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001073 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 }
1075 }
1076
Dan Stozab90cf072015-03-05 11:05:59 -08001077 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001078 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001079 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001080 enableHardwareVsync();
1081 }
1082 }
1083
Pablo Ceballos40845df2016-01-25 17:41:15 -08001084 mFenceTracker.addFrame(refreshStartTime, presentFence,
1085 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1086
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001087 if (mAnimCompositionPending) {
1088 mAnimCompositionPending = false;
1089
Jesse Halla9a1b002013-02-27 16:39:25 -08001090 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001091 mAnimFrameTracker.setActualPresentFence(presentFence);
1092 } else {
1093 // The HWC doesn't support present fences, so use the refresh
1094 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001095 nsecs_t presentTime =
1096 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001097 mAnimFrameTracker.setActualPresentTime(presentTime);
1098 }
1099 mAnimFrameTracker.advanceFrame();
1100 }
Dan Stozab90cf072015-03-05 11:05:59 -08001101
1102 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1103 return;
1104 }
1105
1106 nsecs_t currentTime = systemTime();
1107 if (mHasPoweredOff) {
1108 mHasPoweredOff = false;
1109 } else {
1110 nsecs_t period = mPrimaryDispSync.getPeriod();
1111 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1112 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1113 if (numPeriods < NUM_BUCKETS - 1) {
1114 mFrameBuckets[numPeriods] += elapsedTime;
1115 } else {
1116 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1117 }
1118 mTotalTime += elapsedTime;
1119 }
1120 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001121}
1122
1123void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001124 ATRACE_CALL();
1125 ALOGV("rebuildLayerStacks");
1126
Mathias Agopiancd60f992012-08-16 16:28:27 -07001127 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001128 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001129 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001130 mVisibleRegionsDirty = false;
1131 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001132
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001133 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001134 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001135 Region opaqueRegion;
1136 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001137 Vector<sp<Layer>> layersSortedByZ;
1138 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1139 const Transform& tr(displayDevice->getTransform());
1140 const Rect bounds(displayDevice->getBounds());
1141 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001142 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001143 displayDevice->getLayerStack(), dirtyRegion,
1144 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001145
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001146 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001147 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001148 const sp<Layer>& layer(layers[i]);
1149 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001150 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001151 Region drawRegion(tr.transform(
1152 layer->visibleNonTransparentRegion));
1153 drawRegion.andSelf(bounds);
1154 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001155 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001156 } else {
1157 // Clear out the HWC layer if this layer was
1158 // previously visible, but no longer is
1159 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1160 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001161 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001162 }
1163 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001164 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001165 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1166 displayDevice->undefinedRegion.set(bounds);
1167 displayDevice->undefinedRegion.subtractSelf(
1168 tr.transform(opaqueRegion));
1169 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001170 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001171 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001172}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001173
Mathias Agopiancd60f992012-08-16 16:28:27 -07001174void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001175 ATRACE_CALL();
1176 ALOGV("setUpHWComposer");
1177
Jesse Hall028dc8f2013-08-20 16:35:32 -07001178 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001179 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1180 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1181 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1182
1183 // If nothing has changed (!dirty), don't recompose.
1184 // If something changed, but we don't currently have any visible layers,
1185 // and didn't when we last did a composition, then skip it this time.
1186 // The second rule does two things:
1187 // - When all layers are removed from a display, we'll emit one black
1188 // frame, then nothing more until we get new layers.
1189 // - When a display is created with a private layer stack, we won't
1190 // emit any black frames until a layer is added to the layer stack.
1191 bool mustRecompose = dirty && !(empty && wasEmpty);
1192
1193 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1194 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1195 mustRecompose ? "doing" : "skipping",
1196 dirty ? "+" : "-",
1197 empty ? "+" : "-",
1198 wasEmpty ? "+" : "-");
1199
Dan Stoza71433162014-02-04 16:22:36 -08001200 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001201
1202 if (mustRecompose) {
1203 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1204 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001205 }
1206
Dan Stoza9e56aa02015-11-02 13:00:03 -08001207 // build the h/w work list
1208 if (CC_UNLIKELY(mGeometryInvalid)) {
1209 mGeometryInvalid = false;
1210 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1211 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1212 const auto hwcId = displayDevice->getHwcDisplayId();
1213 if (hwcId >= 0) {
1214 const Vector<sp<Layer>>& currentLayers(
1215 displayDevice->getVisibleLayersSortedByZ());
1216 bool foundLayerWithoutHwc = false;
1217 for (auto& layer : currentLayers) {
1218 if (!layer->hasHwcLayer(hwcId)) {
1219 auto hwcLayer = mHwc->createLayer(hwcId);
1220 if (hwcLayer) {
1221 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1222 } else {
1223 layer->forceClientComposition(hwcId);
1224 foundLayerWithoutHwc = true;
1225 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001226 }
1227 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001228
Dan Stoza9e56aa02015-11-02 13:00:03 -08001229 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001230 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001231 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001232 }
1233 }
1234 }
1235 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001236 }
Riley Andrews03414a12014-07-01 14:22:59 -07001237
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001238
1239 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1240
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 // Set the per-frame data
1242 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1243 auto& displayDevice = mDisplays[displayId];
1244 const auto hwcId = displayDevice->getHwcDisplayId();
1245 if (hwcId < 0) {
1246 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001247 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001248 if (colorMatrix != mPreviousColorMatrix) {
1249 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1250 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1251 "display %zd: %d", displayId, result);
1252 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001253 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1254 layer->setPerFrameData(displayDevice);
1255 }
1256 }
1257
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001258 mPreviousColorMatrix = colorMatrix;
1259
Dan Stoza9e56aa02015-11-02 13:00:03 -08001260 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001261 auto& displayDevice = mDisplays[displayId];
1262 if (!displayDevice->isDisplayOn()) {
1263 continue;
1264 }
1265
1266 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001267 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1268 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001269 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001270}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001271
Mathias Agopiancd60f992012-08-16 16:28:27 -07001272void SurfaceFlinger::doComposition() {
1273 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001274 ALOGV("doComposition");
1275
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001276 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001277 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001278 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001279 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001280 // transform the dirty region into this screen's coordinate space
1281 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001282
1283 // repaint the framebuffer (if needed)
1284 doDisplayComposition(hw, dirtyRegion);
1285
Mathias Agopiancd60f992012-08-16 16:28:27 -07001286 hw->dirtyRegion.clear();
1287 hw->flip(hw->swapRegion);
1288 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001289 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001290 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001291 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001292}
1293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001294void SurfaceFlinger::postFramebuffer()
1295{
Mathias Agopian841cde52012-03-01 15:44:37 -08001296 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001297 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001298
Mathias Agopiana44b0412011-10-16 18:46:35 -07001299 const nsecs_t now = systemTime();
1300 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001301
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1303 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001304 if (!displayDevice->isDisplayOn()) {
1305 continue;
1306 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 const auto hwcId = displayDevice->getHwcDisplayId();
1308 if (hwcId >= 0) {
1309 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001310 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001311 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312 if (displayId == 0) {
1313 // Make the default display current because the VirtualDisplayDevice
1314 // code cannot deal with dequeueBuffer() being called outside of the
1315 // composition loop; however the code below can call glFlush() which
1316 // is allowed to (and does in some case) call dequeueBuffer().
1317 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1318 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1320 sp<Fence> releaseFence = Fence::NO_FENCE;
1321 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1322 releaseFence = displayDevice->getClientTargetAcquireFence();
1323 } else {
1324 auto hwcLayer = layer->getHwcLayer(hwcId);
1325 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001326 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001327 layer->onLayerDisplayed(releaseFence);
1328 }
1329 if (hwcId >= 0) {
1330 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001331 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001332 }
1333
Mathias Agopiana44b0412011-10-16 18:46:35 -07001334 mLastSwapBufferTime = systemTime() - now;
1335 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001336
1337 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1338 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1339 logFrameStats();
1340 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001341}
1342
Mathias Agopian87baae12012-07-31 12:38:26 -07001343void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001344{
Mathias Agopian841cde52012-03-01 15:44:37 -08001345 ATRACE_CALL();
1346
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001347 // here we keep a copy of the drawing state (that is the state that's
1348 // going to be overwritten by handleTransactionLocked()) outside of
1349 // mStateLock so that the side-effects of the State assignment
1350 // don't happen with mStateLock held (which can cause deadlocks).
1351 State drawingState(mDrawingState);
1352
Mathias Agopianca4d3602011-05-19 15:38:14 -07001353 Mutex::Autolock _l(mStateLock);
1354 const nsecs_t now = systemTime();
1355 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001356
Mathias Agopianca4d3602011-05-19 15:38:14 -07001357 // Here we're guaranteed that some transaction flags are set
1358 // so we can call handleTransactionLocked() unconditionally.
1359 // We call getTransactionFlags(), which will also clear the flags,
1360 // with mStateLock held to guarantee that mCurrentState won't change
1361 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001362
Mathias Agopiane57f2922012-08-09 16:29:12 -07001363 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001364 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001365
Mathias Agopianca4d3602011-05-19 15:38:14 -07001366 mLastTransactionTime = systemTime() - now;
1367 mDebugInTransaction = 0;
1368 invalidateHwcGeometry();
1369 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001370}
1371
Mathias Agopian87baae12012-07-31 12:38:26 -07001372void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001373{
1374 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001375 const size_t count = currentLayers.size();
1376
Dan Stoza7dde5992015-05-22 09:51:44 -07001377 // Notify all layers of available frames
1378 for (size_t i = 0; i < count; ++i) {
1379 currentLayers[i]->notifyAvailableFrames();
1380 }
1381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001382 /*
1383 * Traversal of the children
1384 * (perform the transaction for each of them if needed)
1385 */
1386
Mathias Agopian3559b072012-08-15 13:46:03 -07001387 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001388 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001389 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001390 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1391 if (!trFlags) continue;
1392
1393 const uint32_t flags = layer->doTransaction(0);
1394 if (flags & Layer::eVisibleRegion)
1395 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396 }
1397 }
1398
1399 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001400 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401 */
1402
Mathias Agopiane57f2922012-08-09 16:29:12 -07001403 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001404 // here we take advantage of Vector's copy-on-write semantics to
1405 // improve performance by skipping the transaction entirely when
1406 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001407 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1408 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001409 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001410 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001411 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001412 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001413
1414 // find the displays that were removed
1415 // (ie: in drawing state but not in current state)
1416 // also handle displays that changed
1417 // (ie: displays that are in both lists)
1418 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001419 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1420 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001421 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001422 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001423 // Call makeCurrent() on the primary display so we can
1424 // be sure that nothing associated with this display
1425 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001426 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001427 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001428 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1429 if (hw != NULL)
1430 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001431 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001432 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001433 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001434 } else {
1435 ALOGW("trying to remove the main display");
1436 }
1437 } else {
1438 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001439 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001440 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001441 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1442 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001443 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001444 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001445 // recreating the DisplayDevice, so we just remove it
1446 // from the drawing state, so that it get re-added
1447 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001448 sp<DisplayDevice> hw(getDisplayDevice(display));
1449 if (hw != NULL)
1450 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001451 mDisplays.removeItem(display);
1452 mDrawingState.displays.removeItemsAt(i);
1453 dc--; i--;
1454 // at this point we must loop to the next item
1455 continue;
1456 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001457
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001458 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001459 if (disp != NULL) {
1460 if (state.layerStack != draw[i].layerStack) {
1461 disp->setLayerStack(state.layerStack);
1462 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001463 if ((state.orientation != draw[i].orientation)
1464 || (state.viewport != draw[i].viewport)
1465 || (state.frame != draw[i].frame))
1466 {
1467 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001468 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001469 }
Michael Lentine47e45402014-07-18 15:34:25 -07001470 if (state.width != draw[i].width || state.height != draw[i].height) {
1471 disp->setDisplaySize(state.width, state.height);
1472 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001473 }
1474 }
1475 }
1476
1477 // find displays that were added
1478 // (ie: in current state but not in drawing state)
1479 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001480 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001481 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001482
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001483 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001484 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001485 sp<IGraphicBufferProducer> bqProducer;
1486 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001487 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1488 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001489
Dan Stoza9e56aa02015-11-02 13:00:03 -08001490 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001491 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001492 // Virtual displays without a surface are dormant:
1493 // they have external state (layer stack, projection,
1494 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001495 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001496
Dan Stoza1f3efb12014-10-15 16:34:55 -07001497 int width = 0;
1498 int status = state.surface->query(
1499 NATIVE_WINDOW_WIDTH, &width);
1500 ALOGE_IF(status != NO_ERROR,
1501 "Unable to query width (%d)", status);
1502 int height = 0;
1503 status = state.surface->query(
1504 NATIVE_WINDOW_HEIGHT, &height);
1505 ALOGE_IF(status != NO_ERROR,
1506 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001507 int intFormat = 0;
1508 status = state.surface->query(
1509 NATIVE_WINDOW_FORMAT, &intFormat);
1510 ALOGE_IF(status != NO_ERROR,
1511 "Unable to query format (%d)", status);
1512 auto format = static_cast<android_pixel_format_t>(
1513 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001514
Dan Stoza5cf424b2016-05-20 14:02:39 -07001515 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 &hwcId);
1517
Dan Stoza5cf424b2016-05-20 14:02:39 -07001518 // TODO: Plumb requested format back up to consumer
1519
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 sp<VirtualDisplaySurface> vds =
1521 new VirtualDisplaySurface(*mHwc,
1522 hwcId, state.surface, bqProducer,
1523 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001524
1525 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001526 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001527 }
1528 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001529 ALOGE_IF(state.surface!=NULL,
1530 "adding a supported display, but rendering "
1531 "surface is provided (%p), ignoring it",
1532 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001533 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1534 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1535 dispSurface = new FramebufferSurface(*mHwc,
1536 DisplayDevice::DISPLAY_EXTERNAL,
1537 bqConsumer);
1538 producer = bqProducer;
1539 } else {
1540 ALOGE("Attempted to add non-external non-virtual"
1541 " display");
1542 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001543 }
1544
1545 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001546 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001547 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001548 state.type, hwcId, state.isSecure, display,
1549 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001550 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001551 hw->setLayerStack(state.layerStack);
1552 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001553 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001554 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001555 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001556 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001557 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001558 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001559 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001560 }
1561 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001563 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001564
Mathias Agopian84300952012-11-21 16:02:13 -08001565 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1566 // The transform hint might have changed for some layers
1567 // (either because a display has changed, or because a layer
1568 // as changed).
1569 //
1570 // Walk through all the layers in currentLayers,
1571 // and update their transform hint.
1572 //
1573 // If a layer is visible only on a single display, then that
1574 // display is used to calculate the hint, otherwise we use the
1575 // default display.
1576 //
1577 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1578 // the hint is set before we acquire a buffer from the surface texture.
1579 //
1580 // NOTE: layer transactions have taken place already, so we use their
1581 // drawing state. However, SurfaceFlinger's own transaction has not
1582 // happened yet, so we must use the current state layer list
1583 // (soon to become the drawing state list).
1584 //
1585 sp<const DisplayDevice> disp;
1586 uint32_t currentlayerStack = 0;
1587 for (size_t i=0; i<count; i++) {
1588 // NOTE: we rely on the fact that layers are sorted by
1589 // layerStack first (so we don't have to traverse the list
1590 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001591 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001592 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001593 if (i==0 || currentlayerStack != layerStack) {
1594 currentlayerStack = layerStack;
1595 // figure out if this layerstack is mirrored
1596 // (more than one display) if so, pick the default display,
1597 // if not, pick the only display it's on.
1598 disp.clear();
1599 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1600 sp<const DisplayDevice> hw(mDisplays[dpy]);
1601 if (hw->getLayerStack() == currentlayerStack) {
1602 if (disp == NULL) {
1603 disp = hw;
1604 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001605 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001606 break;
1607 }
1608 }
1609 }
1610 }
Chet Haase91d25932013-04-11 15:24:55 -07001611 if (disp == NULL) {
1612 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1613 // redraw after transform hint changes. See bug 8508397.
1614
1615 // could be null when this layer is using a layerStack
1616 // that is not visible on any display. Also can occur at
1617 // screen off/on times.
1618 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001619 }
Chet Haase91d25932013-04-11 15:24:55 -07001620 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001621 }
1622 }
1623
1624
Mathias Agopian3559b072012-08-15 13:46:03 -07001625 /*
1626 * Perform our own transaction if needed
1627 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001628
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001629 const LayerVector& layers(mDrawingState.layersSortedByZ);
1630 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001631 // layers have been added
1632 mVisibleRegionsDirty = true;
1633 }
1634
1635 // some layers might have been removed, so
1636 // we need to update the regions they're exposing.
1637 if (mLayersRemoved) {
1638 mLayersRemoved = false;
1639 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001640 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001641 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001642 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001643 if (currentLayers.indexOf(layer) < 0) {
1644 // this layer is not visible anymore
1645 // TODO: we could traverse the tree from front to back and
1646 // compute the actual visible region
1647 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001648 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001649 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001650 Region(Rect(s.active.w, s.active.h)));
1651 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001654 }
1655
1656 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001657
1658 updateCursorAsync();
1659}
1660
1661void SurfaceFlinger::updateCursorAsync()
1662{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1664 auto& displayDevice = mDisplays[displayId];
1665 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001666 continue;
1667 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001668
1669 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1670 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001671 }
1672 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001673}
1674
1675void SurfaceFlinger::commitTransaction()
1676{
1677 if (!mLayersPendingRemoval.isEmpty()) {
1678 // Notify removed layers now that they can't be drawn from
1679 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001680 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1681 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682 mLayersPendingRemoval[i]->onRemoved();
1683 }
1684 mLayersPendingRemoval.clear();
1685 }
1686
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001687 // If this transaction is part of a window animation then the next frame
1688 // we composite should be considered an animation as well.
1689 mAnimCompositionPending = mAnimTransactionPending;
1690
Mathias Agopian4fec8732012-06-29 14:12:52 -07001691 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001692 mTransactionPending = false;
1693 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001694 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001695}
1696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001697void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001698 const LayerVector& currentLayers, uint32_t layerStack,
1699 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001700{
Mathias Agopian841cde52012-03-01 15:44:37 -08001701 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001702 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001703
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001704 Region aboveOpaqueLayers;
1705 Region aboveCoveredLayers;
1706 Region dirty;
1707
Mathias Agopian87baae12012-07-31 12:38:26 -07001708 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709
1710 size_t i = currentLayers.size();
1711 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001712 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001713
1714 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001715 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001716
Jesse Hall01e29052013-02-19 16:13:35 -08001717 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001718 if (s.layerStack != layerStack)
1719 continue;
1720
Mathias Agopianab028732010-03-16 16:41:46 -07001721 /*
1722 * opaqueRegion: area of a surface that is fully opaque.
1723 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001724 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001725
1726 /*
1727 * visibleRegion: area of a surface that is visible on screen
1728 * and not fully transparent. This is essentially the layer's
1729 * footprint minus the opaque regions above it.
1730 * Areas covered by a translucent surface are considered visible.
1731 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001732 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001733
1734 /*
1735 * coveredRegion: area of a surface that is covered by all
1736 * visible regions above it (which includes the translucent areas).
1737 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001738 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001739
Jesse Halla8026d22012-09-25 13:25:04 -07001740 /*
1741 * transparentRegion: area of a surface that is hinted to be completely
1742 * transparent. This is only used to tell when the layer has no visible
1743 * non-transparent regions and can be removed from the layer list. It
1744 * does not affect the visibleRegion of this layer or any layers
1745 * beneath it. The hint may not be correct if apps don't respect the
1746 * SurfaceView restrictions (which, sadly, some don't).
1747 */
1748 Region transparentRegion;
1749
Mathias Agopianab028732010-03-16 16:41:46 -07001750
1751 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001752 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001753 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001754 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001755 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001756 if (!visibleRegion.isEmpty()) {
1757 // Remove the transparent area from the visible region
1758 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001759 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001760 if (tr.preserveRects()) {
1761 // transform the transparent region
1762 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001763 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001764 // transformation too complex, can't do the
1765 // transparent region optimization.
1766 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001767 }
Mathias Agopianab028732010-03-16 16:41:46 -07001768 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001769
Mathias Agopianab028732010-03-16 16:41:46 -07001770 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001771 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001772 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001773 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1774 // the opaque region is the layer's footprint
1775 opaqueRegion = visibleRegion;
1776 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001777 }
1778 }
1779
Mathias Agopianab028732010-03-16 16:41:46 -07001780 // Clip the covered region to the visible region
1781 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1782
1783 // Update aboveCoveredLayers for next (lower) layer
1784 aboveCoveredLayers.orSelf(visibleRegion);
1785
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 // subtract the opaque region covered by the layers above us
1787 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788
1789 // compute this layer's dirty region
1790 if (layer->contentDirty) {
1791 // we need to invalidate the whole region
1792 dirty = visibleRegion;
1793 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001794 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 layer->contentDirty = false;
1796 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001797 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001798 * the exposed region consists of two components:
1799 * 1) what's VISIBLE now and was COVERED before
1800 * 2) what's EXPOSED now less what was EXPOSED before
1801 *
1802 * note that (1) is conservative, we start with the whole
1803 * visible region but only keep what used to be covered by
1804 * something -- which mean it may have been exposed.
1805 *
1806 * (2) handles areas that were not covered by anything but got
1807 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001808 */
Mathias Agopianab028732010-03-16 16:41:46 -07001809 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001810 const Region oldVisibleRegion = layer->visibleRegion;
1811 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001812 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1813 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 }
1815 dirty.subtractSelf(aboveOpaqueLayers);
1816
1817 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001818 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001819
Mathias Agopianab028732010-03-16 16:41:46 -07001820 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001822
Jesse Halla8026d22012-09-25 13:25:04 -07001823 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824 layer->setVisibleRegion(visibleRegion);
1825 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001826 layer->setVisibleNonTransparentRegion(
1827 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828 }
1829
Mathias Agopian87baae12012-07-31 12:38:26 -07001830 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831}
1832
Mathias Agopian87baae12012-07-31 12:38:26 -07001833void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1834 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001835 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001836 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1837 if (hw->getLayerStack() == layerStack) {
1838 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001839 }
1840 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001841}
1842
Dan Stoza6b9454d2014-11-07 16:00:59 -08001843bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001844{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001845 ALOGV("handlePageFlip");
1846
Mathias Agopian4fec8732012-06-29 14:12:52 -07001847 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001848
Mathias Agopian4fec8732012-06-29 14:12:52 -07001849 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001850 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001851 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001852
1853 // Store the set of layers that need updates. This set must not change as
1854 // buffers are being latched, as this could result in a deadlock.
1855 // Example: Two producers share the same command stream and:
1856 // 1.) Layer 0 is latched
1857 // 2.) Layer 0 gets a new frame
1858 // 2.) Layer 1 gets a new frame
1859 // 3.) Layer 1 is latched.
1860 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1861 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001862 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001863 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001864 if (layer->hasQueuedFrame()) {
1865 frameQueued = true;
1866 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001868 } else {
1869 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001870 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001871 } else {
1872 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001873 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001874 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001876 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001877 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001878 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001879 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001880 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001881
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001882 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001883
1884 // If we will need to wake up at some time in the future to deal with a
1885 // queued frame that shouldn't be displayed during this vsync period, wake
1886 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001888 signalLayerUpdate();
1889 }
1890
1891 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893}
1894
Mathias Agopianad456f92011-01-13 17:53:01 -08001895void SurfaceFlinger::invalidateHwcGeometry()
1896{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001898}
1899
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001900
Mathias Agopiancd60f992012-08-16 16:28:27 -07001901void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001902 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001903{
Dan Stoza71433162014-02-04 16:22:36 -08001904 // We only need to actually compose the display if:
1905 // 1) It is being handled by hardware composer, which may need this to
1906 // keep its virtual display state machine in sync, or
1907 // 2) There is work to be done (the dirty region isn't empty)
1908 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1909 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001911 return;
1912 }
1913
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 ALOGV("doDisplayComposition");
1915
Mathias Agopian87baae12012-07-31 12:38:26 -07001916 Region dirtyRegion(inDirtyRegion);
1917
Mathias Agopianb8a55602009-06-26 19:06:36 -07001918 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001919 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001920
Mathias Agopian42977342012-08-05 00:40:46 -07001921 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001922 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001923 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1924 // takes a rectangle, we must make sure to update that whole
1925 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001926 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001927 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001928 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001929 // We need to redraw the rectangle that will be updated
1930 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001931 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001932 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001933 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001934 } else {
1935 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001936 dirtyRegion.set(hw->bounds());
1937 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938 }
1939 }
1940
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001941 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001942
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001943 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001944 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001945
1946 // swap buffers (presentation)
1947 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948}
1949
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950bool SurfaceFlinger::doComposeSurfaces(
1951 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001952{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001954
Dan Stoza9e56aa02015-11-02 13:00:03 -08001955 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001956
1957 mat4 oldColorMatrix;
1958 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
1959 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
1960 if (applyColorMatrix) {
1961 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1962 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
1963 }
1964
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1966 if (hasClientComposition) {
1967 ALOGV("hasClientComposition");
1968
1969 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001970 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001971 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001972 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1973 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1974 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1975 }
1976 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001977 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001978
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001979 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1981 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001982 // when using overlays, we assume a fully transparent framebuffer
1983 // NOTE: we could reduce how much we need to clear, for instance
1984 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001985 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001986 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001987 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001988 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001989 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001991
1992 // we remove the scissor part
1993 // we're left with the letterbox region
1994 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001996
1997 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001998 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001999
2000 // but limit it to the dirty region
2001 region.andSelf(dirty);
2002
Mathias Agopianb9494d52012-04-18 02:28:45 -07002003 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002004 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002005 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002007 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002008 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002009
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002011 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002012 // scissor on the main display. It should never be needed
2013 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 const Rect& bounds(displayDevice->getBounds());
2015 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002016 if (scissor != bounds) {
2017 // scissor doesn't match the screen's dimensions, so we
2018 // need to clear everything outside of it and enable
2019 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002020
Mathias Agopianf45c5102012-10-24 16:29:17 -07002021 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002022 const uint32_t height = displayDevice->getHeight();
2023 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002024 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002025 }
2026 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002027 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002028
Mathias Agopian85d751c2012-08-29 16:59:24 -07002029 /*
2030 * and then, render the layers targeted at the framebuffer
2031 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002032
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 ALOGV("Rendering client layers");
2034 const Transform& displayTransform = displayDevice->getTransform();
2035 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002036 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 bool firstLayer = true;
2038 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2039 const Region clip(dirty.intersect(
2040 displayTransform.transform(layer->visibleRegion)));
2041 ALOGV("Layer: %s", layer->getName().string());
2042 ALOGV(" Composition type: %s",
2043 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002044 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 switch (layer->getCompositionType(hwcId)) {
2046 case HWC2::Composition::Cursor:
2047 case HWC2::Composition::Device:
2048 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002049 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2051 layer->isOpaque(state) && (state.alpha == 1.0f)
2052 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053 // never clear the very first layer since we're
2054 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002056 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002057 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002058 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 case HWC2::Composition::Client: {
2060 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002061 break;
2062 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002063 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002064 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002065 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002066 } else {
2067 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002068 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002070 }
2071 } else {
2072 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002074 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002076 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002077 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002078 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002079 }
2080 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002081
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002082 if (applyColorMatrix) {
2083 getRenderEngine().setupColorTransform(oldColorMatrix);
2084 }
2085
Mathias Agopianf45c5102012-10-24 16:29:17 -07002086 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002088 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002089}
2090
Mathias Agopian3f844832013-08-07 21:24:32 -07002091void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002092 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002093 RenderEngine& engine(getRenderEngine());
2094 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002095}
2096
Dan Stoza7d89d062015-04-30 13:29:25 -07002097status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002098 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002099 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002100 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002101{
Dan Stoza7d89d062015-04-30 13:29:25 -07002102 // add this layer to the current state list
2103 {
2104 Mutex::Autolock _l(mStateLock);
2105 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2106 return NO_MEMORY;
2107 }
2108 mCurrentState.layersSortedByZ.add(lbc);
2109 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2110 }
2111
Mathias Agopian96f08192010-06-02 23:28:45 -07002112 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002113 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002114
Dan Stoza7d89d062015-04-30 13:29:25 -07002115 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002116}
2117
Mathias Agopian3f844832013-08-07 21:24:32 -07002118status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002120 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002122 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002123 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002124 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002125 return NO_ERROR;
2126 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002127 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128}
2129
Dan Stozac7014012014-02-14 15:03:43 -08002130uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002131 return android_atomic_release_load(&mTransactionFlags);
2132}
2133
Mathias Agopian3f844832013-08-07 21:24:32 -07002134uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2136}
2137
Mathias Agopian3f844832013-08-07 21:24:32 -07002138uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2140 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002141 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142 }
2143 return old;
2144}
2145
Mathias Agopian8b33f032012-07-24 20:43:54 -07002146void SurfaceFlinger::setTransactionState(
2147 const Vector<ComposerState>& state,
2148 const Vector<DisplayState>& displays,
2149 uint32_t flags)
2150{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002151 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002152 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002153 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002154
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002155 if (flags & eAnimation) {
2156 // For window updates that are part of an animation we must wait for
2157 // previous animation "frames" to be handled.
2158 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002159 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002160 if (CC_UNLIKELY(err != NO_ERROR)) {
2161 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002162 // caller after a few seconds.
2163 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2164 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002165 mAnimTransactionPending = false;
2166 break;
2167 }
2168 }
2169 }
2170
Mathias Agopiane57f2922012-08-09 16:29:12 -07002171 size_t count = displays.size();
2172 for (size_t i=0 ; i<count ; i++) {
2173 const DisplayState& s(displays[i]);
2174 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002175 }
2176
Mathias Agopiane57f2922012-08-09 16:29:12 -07002177 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002178 for (size_t i=0 ; i<count ; i++) {
2179 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002180 // Here we need to check that the interface we're given is indeed
2181 // one of our own. A malicious client could give us a NULL
2182 // IInterface, or one of its own or even one of our own but a
2183 // different type. All these situations would cause us to crash.
2184 //
2185 // NOTE: it would be better to use RTTI as we could directly check
2186 // that we have a Client*. however, RTTI is disabled in Android.
2187 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002188 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002189 if (binder != NULL) {
2190 String16 desc(binder->getInterfaceDescriptor());
2191 if (desc == ISurfaceComposerClient::descriptor) {
2192 sp<Client> client( static_cast<Client *>(s.client.get()) );
2193 transactionFlags |= setClientStateLocked(client, s.state);
2194 }
2195 }
2196 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002197 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002198
Robert Carr2a7dbb42016-05-24 11:41:28 -07002199 // If a synchronous transaction is explicitly requested without any changes,
2200 // force a transaction anyway. This can be used as a flush mechanism for
2201 // previous async transactions.
2202 if (transactionFlags == 0 && (flags & eSynchronous)) {
2203 transactionFlags = eTransactionNeeded;
2204 }
2205
Mathias Agopian386aa982011-11-07 21:58:03 -08002206 if (transactionFlags) {
2207 // this triggers the transaction
2208 setTransactionFlags(transactionFlags);
2209
2210 // if this is a synchronous transaction, wait for it to take effect
2211 // before returning.
2212 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002213 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002214 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002215 if (flags & eAnimation) {
2216 mAnimTransactionPending = true;
2217 }
2218 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002219 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2220 if (CC_UNLIKELY(err != NO_ERROR)) {
2221 // just in case something goes wrong in SF, return to the
2222 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002223 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2224 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002225 break;
2226 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 }
2229}
2230
Mathias Agopiane57f2922012-08-09 16:29:12 -07002231uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2232{
Jesse Hall9a143922012-10-04 16:29:19 -07002233 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2234 if (dpyIdx < 0)
2235 return 0;
2236
Mathias Agopiane57f2922012-08-09 16:29:12 -07002237 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002238 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002239 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002240 const uint32_t what = s.what;
2241 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002242 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002243 disp.surface = s.surface;
2244 flags |= eDisplayTransactionNeeded;
2245 }
2246 }
2247 if (what & DisplayState::eLayerStackChanged) {
2248 if (disp.layerStack != s.layerStack) {
2249 disp.layerStack = s.layerStack;
2250 flags |= eDisplayTransactionNeeded;
2251 }
2252 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002253 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002254 if (disp.orientation != s.orientation) {
2255 disp.orientation = s.orientation;
2256 flags |= eDisplayTransactionNeeded;
2257 }
2258 if (disp.frame != s.frame) {
2259 disp.frame = s.frame;
2260 flags |= eDisplayTransactionNeeded;
2261 }
2262 if (disp.viewport != s.viewport) {
2263 disp.viewport = s.viewport;
2264 flags |= eDisplayTransactionNeeded;
2265 }
2266 }
Michael Lentine47e45402014-07-18 15:34:25 -07002267 if (what & DisplayState::eDisplaySizeChanged) {
2268 if (disp.width != s.width) {
2269 disp.width = s.width;
2270 flags |= eDisplayTransactionNeeded;
2271 }
2272 if (disp.height != s.height) {
2273 disp.height = s.height;
2274 flags |= eDisplayTransactionNeeded;
2275 }
2276 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002277 }
2278 return flags;
2279}
2280
2281uint32_t SurfaceFlinger::setClientStateLocked(
2282 const sp<Client>& client,
2283 const layer_state_t& s)
2284{
2285 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002286 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002287 if (layer != 0) {
2288 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002289 bool geometryAppliesWithResize =
2290 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002291 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002292 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002293 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002294 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002295 }
2296 if (what & layer_state_t::eLayerChanged) {
2297 // NOTE: index needs to be calculated before we update the state
2298 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002299 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002300 mCurrentState.layersSortedByZ.removeAt(idx);
2301 mCurrentState.layersSortedByZ.add(layer);
2302 // we need traversal (state changed)
2303 // AND transaction (list changed)
2304 flags |= eTransactionNeeded|eTraversalNeeded;
2305 }
2306 }
2307 if (what & layer_state_t::eSizeChanged) {
2308 if (layer->setSize(s.w, s.h)) {
2309 flags |= eTraversalNeeded;
2310 }
2311 }
2312 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002313 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002314 flags |= eTraversalNeeded;
2315 }
2316 if (what & layer_state_t::eMatrixChanged) {
2317 if (layer->setMatrix(s.matrix))
2318 flags |= eTraversalNeeded;
2319 }
2320 if (what & layer_state_t::eTransparentRegionChanged) {
2321 if (layer->setTransparentRegionHint(s.transparentRegion))
2322 flags |= eTraversalNeeded;
2323 }
Dan Stoza23116082015-06-18 14:58:39 -07002324 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002325 if (layer->setFlags(s.flags, s.mask))
2326 flags |= eTraversalNeeded;
2327 }
2328 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002329 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002330 flags |= eTraversalNeeded;
2331 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002332 if (what & layer_state_t::eFinalCropChanged) {
2333 if (layer->setFinalCrop(s.finalCrop))
2334 flags |= eTraversalNeeded;
2335 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002336 if (what & layer_state_t::eLayerStackChanged) {
2337 // NOTE: index needs to be calculated before we update the state
2338 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002339 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002340 mCurrentState.layersSortedByZ.removeAt(idx);
2341 mCurrentState.layersSortedByZ.add(layer);
2342 // we need traversal (state changed)
2343 // AND transaction (list changed)
2344 flags |= eTransactionNeeded|eTraversalNeeded;
2345 }
2346 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002347 if (what & layer_state_t::eDeferTransaction) {
2348 layer->deferTransactionUntil(s.handle, s.frameNumber);
2349 // We don't trigger a traversal here because if no other state is
2350 // changed, we don't want this to cause any more work
2351 }
Robert Carrc3574f72016-03-24 12:19:32 -07002352 if (what & layer_state_t::eOverrideScalingModeChanged) {
2353 layer->setOverrideScalingMode(s.overrideScalingMode);
2354 // We don't trigger a traversal here because if no other state is
2355 // changed, we don't want this to cause any more work
2356 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002357 }
2358 return flags;
2359}
2360
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002361status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002362 const String8& name,
2363 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002364 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2365 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002367 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002368 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002369 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002370 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002371 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002372 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002373
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002374 status_t result = NO_ERROR;
2375
2376 sp<Layer> layer;
2377
Mathias Agopian3165cc22012-08-08 19:42:09 -07002378 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2379 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002380 result = createNormalLayer(client,
2381 name, w, h, flags, format,
2382 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002383 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002384 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002385 result = createDimLayer(client,
2386 name, w, h, flags,
2387 handle, gbp, &layer);
2388 break;
2389 default:
2390 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391 break;
2392 }
2393
Dan Stoza7d89d062015-04-30 13:29:25 -07002394 if (result != NO_ERROR) {
2395 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002397
2398 result = addClientLayer(client, *handle, *gbp, layer);
2399 if (result != NO_ERROR) {
2400 return result;
2401 }
2402
2403 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002404 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405}
2406
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002407status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2408 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2409 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410{
2411 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002412 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413 case PIXEL_FORMAT_TRANSPARENT:
2414 case PIXEL_FORMAT_TRANSLUCENT:
2415 format = PIXEL_FORMAT_RGBA_8888;
2416 break;
2417 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002418 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419 break;
2420 }
2421
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002422 *outLayer = new Layer(this, client, name, w, h, flags);
2423 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2424 if (err == NO_ERROR) {
2425 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002426 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002428
2429 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2430 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002431}
2432
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002433status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2434 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2435 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002437 *outLayer = new LayerDim(this, client, name, w, h, flags);
2438 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002439 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002440 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002441}
2442
Mathias Agopianac9fa422013-02-11 16:40:36 -08002443status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002444{
Mathias Agopian67106042013-03-14 19:18:13 -07002445 // called by the window manager when it wants to remove a Layer
2446 status_t err = NO_ERROR;
2447 sp<Layer> l(client->getLayerUser(handle));
2448 if (l != NULL) {
2449 err = removeLayer(l);
2450 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2451 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002452 }
2453 return err;
2454}
2455
Mathias Agopian13127d82013-03-05 17:47:11 -08002456status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002457{
Mathias Agopian67106042013-03-14 19:18:13 -07002458 // called by ~LayerCleaner() when all references to the IBinder (handle)
2459 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002460 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002461 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002462 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002463 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002464 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002465 "error removing layer=%p (%s)", l.get(), strerror(-err));
2466 }
2467 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468}
2469
Mathias Agopianb60314a2012-04-10 22:09:54 -07002470// ---------------------------------------------------------------------------
2471
Andy McFadden13a082e2012-08-24 10:16:42 -07002472void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002473 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002474 Vector<ComposerState> state;
2475 Vector<DisplayState> displays;
2476 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002477 d.what = DisplayState::eDisplayProjectionChanged |
2478 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002479 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002480 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002481 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002482 d.frame.makeInvalid();
2483 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002484 d.width = 0;
2485 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002486 displays.add(d);
2487 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002488 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002489
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2491 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002492 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002493}
2494
2495void SurfaceFlinger::initializeDisplays() {
2496 class MessageScreenInitialized : public MessageBase {
2497 SurfaceFlinger* flinger;
2498 public:
2499 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2500 virtual bool handler() {
2501 flinger->onInitializeDisplays();
2502 return true;
2503 }
2504 };
2505 sp<MessageBase> msg = new MessageScreenInitialized(this);
2506 postMessageAsync(msg); // we may be called from main thread, use async message
2507}
2508
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002509void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2510 int mode) {
2511 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2512 this);
2513 int32_t type = hw->getDisplayType();
2514 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002515
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002516 if (mode == currentMode) {
2517 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002518 return;
2519 }
2520
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002521 hw->setPowerMode(mode);
2522 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2523 ALOGW("Trying to set power mode for virtual display");
2524 return;
2525 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002526
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002527 if (currentMode == HWC_POWER_MODE_OFF) {
2528 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002529 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2530 // FIXME: eventthread only knows about the main display right now
2531 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002532 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002534
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002535 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002536 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002537 repaintEverything();
2538 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002539 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002540 disableHardwareVsync(true); // also cancels any in-progress resync
2541
Mathias Agopiancde87a32012-09-13 14:09:01 -07002542 // FIXME: eventthread only knows about the main display right now
2543 mEventThread->onScreenReleased();
2544 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002545
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002546 getHwComposer().setPowerMode(type, mode);
2547 mVisibleRegionsDirty = true;
2548 // from this point on, SF will stop drawing on this display
2549 } else {
2550 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002551 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002552}
2553
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002554void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2555 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002556 SurfaceFlinger& mFlinger;
2557 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002558 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002559 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002560 MessageSetPowerMode(SurfaceFlinger& flinger,
2561 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2562 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002563 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002564 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002565 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002566 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002567 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002568 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002569 ALOGW("Attempt to set power mode = %d for virtual display",
2570 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002571 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002572 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002573 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002574 return true;
2575 }
2576 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002577 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002578 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002579}
2580
2581// ---------------------------------------------------------------------------
2582
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2584{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002586
Mathias Agopianbd115332013-04-18 16:41:04 -07002587 IPCThreadState* ipc = IPCThreadState::self();
2588 const int pid = ipc->getCallingPid();
2589 const int uid = ipc->getCallingUid();
2590 if ((uid != AID_SHELL) &&
2591 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002592 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002593 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002595 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002596 // (this would indicate SF is stuck, but we want to be able to
2597 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002598 status_t err = mStateLock.timedLock(s2ns(1));
2599 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002600 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002601 result.appendFormat(
2602 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2603 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002604 }
2605
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002606 bool dumpAll = true;
2607 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002608 size_t numArgs = args.size();
2609 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002610 if ((index < numArgs) &&
2611 (args[index] == String16("--list"))) {
2612 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002613 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002614 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002615 }
2616
2617 if ((index < numArgs) &&
2618 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002619 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002620 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002621 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002622 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002623
2624 if ((index < numArgs) &&
2625 (args[index] == String16("--latency-clear"))) {
2626 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002627 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002628 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002629 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002630
2631 if ((index < numArgs) &&
2632 (args[index] == String16("--dispsync"))) {
2633 index++;
2634 mPrimaryDispSync.dump(result);
2635 dumpAll = false;
2636 }
Dan Stozab90cf072015-03-05 11:05:59 -08002637
2638 if ((index < numArgs) &&
2639 (args[index] == String16("--static-screen"))) {
2640 index++;
2641 dumpStaticScreenStats(result);
2642 dumpAll = false;
2643 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002644
2645 if ((index < numArgs) &&
2646 (args[index] == String16("--fences"))) {
2647 index++;
2648 mFenceTracker.dump(&result);
2649 dumpAll = false;
2650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002653 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002654 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002655 }
2656
Mathias Agopian9795c422009-08-26 16:36:26 -07002657 if (locked) {
2658 mStateLock.unlock();
2659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 }
2661 write(fd, result.string(), result.size());
2662 return NO_ERROR;
2663}
2664
Dan Stozac7014012014-02-14 15:03:43 -08002665void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2666 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002667{
2668 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2669 const size_t count = currentLayers.size();
2670 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002671 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002672 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002673 }
2674}
2675
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002676void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002677 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002678{
2679 String8 name;
2680 if (index < args.size()) {
2681 name = String8(args[index]);
2682 index++;
2683 }
2684
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2686 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002687 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002688
2689 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002690 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002691 } else {
2692 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2693 const size_t count = currentLayers.size();
2694 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002695 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002696 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002697 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002698 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002699 }
2700 }
2701}
2702
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002703void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002704 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002705{
2706 String8 name;
2707 if (index < args.size()) {
2708 name = String8(args[index]);
2709 index++;
2710 }
2711
2712 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2713 const size_t count = currentLayers.size();
2714 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002715 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002716 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002717 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002718 }
2719 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002720
Svetoslavd85084b2014-03-20 10:28:31 -07002721 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002722}
2723
Jamie Gennis6547ff42013-07-16 20:12:42 -07002724// This should only be called from the main thread. Otherwise it would need
2725// the lock and should use mCurrentState rather than mDrawingState.
2726void SurfaceFlinger::logFrameStats() {
2727 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2728 const size_t count = drawingLayers.size();
2729 for (size_t i=0 ; i<count ; i++) {
2730 const sp<Layer>& layer(drawingLayers[i]);
2731 layer->logFrameStats();
2732 }
2733
2734 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2735}
2736
Andy McFadden4803b742012-09-24 19:07:20 -07002737/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2738{
2739 static const char* config =
2740 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002741#ifdef HAS_CONTEXT_PRIORITY
2742 " HAS_CONTEXT_PRIORITY"
2743#endif
2744#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2745 " NEVER_DEFAULT_TO_ASYNC_MODE"
2746#endif
2747#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2748 " TARGET_DISABLE_TRIPLE_BUFFERING"
2749#endif
2750 "]";
2751 result.append(config);
2752}
2753
Dan Stozab90cf072015-03-05 11:05:59 -08002754void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2755{
2756 result.appendFormat("Static screen stats:\n");
2757 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2758 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2759 float percent = 100.0f *
2760 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2761 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2762 b + 1, bucketTimeSec, percent);
2763 }
2764 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2765 float percent = 100.0f *
2766 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2767 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2768 NUM_BUCKETS - 1, bucketTimeSec, percent);
2769}
2770
Dan Stozae77c7662016-05-13 11:37:28 -07002771void SurfaceFlinger::recordBufferingStats(const char* layerName,
2772 std::vector<OccupancyTracker::Segment>&& history) {
2773 Mutex::Autolock lock(mBufferingStatsMutex);
2774 auto& stats = mBufferingStats[layerName];
2775 for (const auto& segment : history) {
2776 if (!segment.usedThirdBuffer) {
2777 stats.twoBufferTime += segment.totalTime;
2778 }
2779 if (segment.occupancyAverage < 1.0f) {
2780 stats.doubleBufferedTime += segment.totalTime;
2781 } else if (segment.occupancyAverage < 2.0f) {
2782 stats.tripleBufferedTime += segment.totalTime;
2783 }
2784 ++stats.numSegments;
2785 stats.totalTime += segment.totalTime;
2786 }
2787}
2788
2789void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2790 result.append("Buffering stats:\n");
2791 result.append(" [Layer name] <Active time> <Two buffer> "
2792 "<Double buffered> <Triple buffered>\n");
2793 Mutex::Autolock lock(mBufferingStatsMutex);
2794 typedef std::tuple<std::string, float, float, float> BufferTuple;
2795 std::map<float, BufferTuple, std::greater<float>> sorted;
2796 for (const auto& statsPair : mBufferingStats) {
2797 const char* name = statsPair.first.c_str();
2798 const BufferingStats& stats = statsPair.second;
2799 if (stats.numSegments == 0) {
2800 continue;
2801 }
2802 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2803 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2804 stats.totalTime;
2805 float doubleBufferRatio = static_cast<float>(
2806 stats.doubleBufferedTime) / stats.totalTime;
2807 float tripleBufferRatio = static_cast<float>(
2808 stats.tripleBufferedTime) / stats.totalTime;
2809 sorted.insert({activeTime, {name, twoBufferRatio,
2810 doubleBufferRatio, tripleBufferRatio}});
2811 }
2812 for (const auto& sortedPair : sorted) {
2813 float activeTime = sortedPair.first;
2814 const BufferTuple& values = sortedPair.second;
2815 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2816 std::get<0>(values).c_str(), activeTime,
2817 std::get<1>(values), std::get<2>(values),
2818 std::get<3>(values));
2819 }
2820 result.append("\n");
2821}
2822
2823
Mathias Agopian74d211a2013-04-22 16:55:35 +02002824void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2825 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002826{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002827 bool colorize = false;
2828 if (index < args.size()
2829 && (args[index] == String16("--color"))) {
2830 colorize = true;
2831 index++;
2832 }
2833
2834 Colorizer colorizer(colorize);
2835
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002836 // figure out if we're stuck somewhere
2837 const nsecs_t now = systemTime();
2838 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2839 const nsecs_t inTransaction(mDebugInTransaction);
2840 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2841 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2842
2843 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002844 * Dump library configuration.
2845 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002846
2847 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002848 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002849 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002850 appendSfConfigString(result);
2851 appendUiConfigString(result);
2852 appendGuiConfigString(result);
2853 result.append("\n");
2854
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002855 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002856 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002857 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002858 result.append(SyncFeatures::getInstance().toString());
2859 result.append("\n");
2860
Dan Stoza9e56aa02015-11-02 13:00:03 -08002861 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2862
Andy McFadden41d67d72014-04-25 16:58:34 -07002863 colorizer.bold(result);
2864 result.append("DispSync configuration: ");
2865 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002866 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2867 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002868 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2869 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002870 result.append("\n");
2871
Dan Stozab90cf072015-03-05 11:05:59 -08002872 // Dump static screen stats
2873 result.append("\n");
2874 dumpStaticScreenStats(result);
2875 result.append("\n");
2876
Dan Stozae77c7662016-05-13 11:37:28 -07002877 dumpBufferingStats(result);
2878
Andy McFadden4803b742012-09-24 19:07:20 -07002879 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002880 * Dump the visible layer list
2881 */
2882 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2883 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002884 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002885 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002886 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002887 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002888 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002889 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002890 }
2891
2892 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002893 * Dump Display state
2894 */
2895
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002896 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002897 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002898 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002899 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2900 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002901 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002902 }
2903
2904 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002905 * Dump SurfaceFlinger global state
2906 */
2907
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002908 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002909 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002910 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002911
Mathias Agopian888c8222012-08-04 21:10:38 -07002912 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002913 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002914
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002915 colorizer.bold(result);
2916 result.appendFormat("EGL implementation : %s\n",
2917 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2918 colorizer.reset(result);
2919 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002920 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002921
Mathias Agopian875d8e12013-06-07 15:35:48 -07002922 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002923
Mathias Agopian42977342012-08-05 00:40:46 -07002924 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002925 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2926 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002927 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002928 " last eglSwapBuffers() time: %f us\n"
2929 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002930 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002931 " refresh-rate : %f fps\n"
2932 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002933 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002934 " gpu_to_cpu_unsupported : %d\n"
2935 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002936 mLastSwapBufferTime/1000.0,
2937 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002938 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002939 1e9 / activeConfig->getVsyncPeriod(),
2940 activeConfig->getDpiX(),
2941 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002942 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002943
Mathias Agopian74d211a2013-04-22 16:55:35 +02002944 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002945 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002946
Mathias Agopian74d211a2013-04-22 16:55:35 +02002947 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002948 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002949
2950 /*
2951 * VSYNC state
2952 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002953 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002954
2955 /*
2956 * Dump HWComposer state
2957 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002958 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002959 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002960 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002961 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002962 result.appendFormat(" h/w composer %s\n",
2963 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002964 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002965
2966 /*
2967 * Dump gralloc state
2968 */
2969 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2970 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002971}
2972
Mathias Agopian13127d82013-03-05 17:47:11 -08002973const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002974SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002975 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002976 wp<IBinder> dpy;
2977 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2978 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2979 dpy = mDisplays.keyAt(i);
2980 break;
2981 }
2982 }
2983 if (dpy == NULL) {
2984 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2985 // Just use the primary display so we have something to return
2986 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2987 }
2988 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002989}
2990
Keun young Park63f165f2012-08-31 10:53:36 -07002991bool SurfaceFlinger::startDdmConnection()
2992{
2993 void* libddmconnection_dso =
2994 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2995 if (!libddmconnection_dso) {
2996 return false;
2997 }
2998 void (*DdmConnection_start)(const char* name);
2999 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003000 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003001 if (!DdmConnection_start) {
3002 dlclose(libddmconnection_dso);
3003 return false;
3004 }
3005 (*DdmConnection_start)(getServiceName());
3006 return true;
3007}
3008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009status_t SurfaceFlinger::onTransact(
3010 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3011{
3012 switch (code) {
3013 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003014 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003015 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003017 case CLEAR_ANIMATION_FRAME_STATS:
3018 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003019 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003020 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021 {
3022 // codes that require permission check
3023 IPCThreadState* ipc = IPCThreadState::self();
3024 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003025 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003026 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003027 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003028 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003029 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3030 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003031 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003032 break;
3033 }
3034 case CAPTURE_SCREEN:
3035 {
3036 // codes that require permission check
3037 IPCThreadState* ipc = IPCThreadState::self();
3038 const int pid = ipc->getCallingPid();
3039 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003040 if ((uid != AID_GRAPHICS) &&
3041 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003042 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003043 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3044 return PERMISSION_DENIED;
3045 }
3046 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047 }
3048 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003049
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3051 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003052 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003053 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003054 IPCThreadState* ipc = IPCThreadState::self();
3055 const int pid = ipc->getCallingPid();
3056 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003057 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003058 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 return PERMISSION_DENIED;
3060 }
3061 int n;
3062 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003063 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003064 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 return NO_ERROR;
3066 case 1002: // SHOW_UPDATES
3067 n = data.readInt32();
3068 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003069 invalidateHwcGeometry();
3070 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003073 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003074 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003076 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 setTransactionFlags(
3078 eTransactionNeeded|
3079 eDisplayTransactionNeeded|
3080 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003081 return NO_ERROR;
3082 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003083 case 1006:{ // send empty update
3084 signalRefresh();
3085 return NO_ERROR;
3086 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003087 case 1008: // toggle use of hw composer
3088 n = data.readInt32();
3089 mDebugDisableHWC = n ? 1 : 0;
3090 invalidateHwcGeometry();
3091 repaintEverything();
3092 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003093 case 1009: // toggle use of transform hint
3094 n = data.readInt32();
3095 mDebugDisableTransformHint = n ? 1 : 0;
3096 invalidateHwcGeometry();
3097 repaintEverything();
3098 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003099 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003100 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 reply->writeInt32(0);
3102 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003103 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003104 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003105 return NO_ERROR;
3106 case 1013: {
3107 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003108 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3109 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003110 return NO_ERROR;
3111 }
3112 case 1014: {
3113 // daltonize
3114 n = data.readInt32();
3115 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003116 case 1:
3117 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3118 break;
3119 case 2:
3120 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3121 break;
3122 case 3:
3123 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3124 break;
3125 default:
3126 mDaltonizer.setType(ColorBlindnessType::None);
3127 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003128 }
3129 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003130 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003131 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003132 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003133 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003134 invalidateHwcGeometry();
3135 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003136 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003137 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003138 case 1015: {
3139 // apply a color matrix
3140 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003141 if (n) {
3142 // color matrix is sent as mat3 matrix followed by vec3
3143 // offset, then packed into a mat4 where the last row is
3144 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003145 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003146 for (size_t j = 0; j < 4; j++) {
3147 mColorMatrix[i][j] = data.readFloat();
3148 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003149 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003150 } else {
3151 mColorMatrix = mat4();
3152 }
3153 invalidateHwcGeometry();
3154 repaintEverything();
3155 return NO_ERROR;
3156 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003157 // This is an experimental interface
3158 // Needs to be shifted to proper binder interface when we productize
3159 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003160 n = data.readInt32();
3161 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003162 return NO_ERROR;
3163 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003164 case 1017: {
3165 n = data.readInt32();
3166 mForceFullDamage = static_cast<bool>(n);
3167 return NO_ERROR;
3168 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003169 case 1018: { // Modify Choreographer's phase offset
3170 n = data.readInt32();
3171 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3172 return NO_ERROR;
3173 }
3174 case 1019: { // Modify SurfaceFlinger's phase offset
3175 n = data.readInt32();
3176 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3177 return NO_ERROR;
3178 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
3180 }
3181 return err;
3182}
3183
Mathias Agopian53331da2011-08-22 21:44:41 -07003184void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003185 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003186 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003187}
3188
Mathias Agopian59119e62010-10-11 12:37:43 -07003189// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003190// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003191// ---------------------------------------------------------------------------
3192
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003193/* The code below is here to handle b/8734824
3194 *
3195 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003196 * from the surfaceflinger thread to the calling binder thread, where they
3197 * are executed. This allows the calling thread in the calling process to be
3198 * reused and not depend on having "enough" binder threads to handle the
3199 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003200 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003201class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003202 /* Parts of GraphicProducerWrapper are run on two different threads,
3203 * communicating by sending messages via Looper but also by shared member
3204 * data. Coherence maintenance is subtle and in places implicit (ugh).
3205 *
3206 * Don't rely on Looper's sendMessage/handleMessage providing
3207 * release/acquire semantics for any data not actually in the Message.
3208 * Data going from surfaceflinger to binder threads needs to be
3209 * synchronized explicitly.
3210 *
3211 * Barrier open/wait do provide release/acquire semantics. This provides
3212 * implicit synchronization for data coming back from binder to
3213 * surfaceflinger threads.
3214 */
3215
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003216 sp<IGraphicBufferProducer> impl;
3217 sp<Looper> looper;
3218 status_t result;
3219 bool exitPending;
3220 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003221 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003222 uint32_t code;
3223 Parcel const* data;
3224 Parcel* reply;
3225
3226 enum {
3227 MSG_API_CALL,
3228 MSG_EXIT
3229 };
3230
3231 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003232 * Called on surfaceflinger thread. This is called by our "fake"
3233 * BpGraphicBufferProducer. We package the data and reply Parcel and
3234 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003235 */
3236 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003237 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003238 this->code = code;
3239 this->data = &data;
3240 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003241 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003242 // if we've exited, we run the message synchronously right here.
3243 // note (JH): as far as I can tell from looking at the code, this
3244 // never actually happens. if it does, i'm not sure if it happens
3245 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003246 handleMessage(Message(MSG_API_CALL));
3247 } else {
3248 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003249 // Prevent stores to this->{code, data, reply} from being
3250 // reordered later than the construction of Message.
3251 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003252 looper->sendMessage(this, Message(MSG_API_CALL));
3253 barrier.wait();
3254 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003255 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003256 }
3257
3258 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003259 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003260 * call the real BpGraphicBufferProducer.
3261 */
3262 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003263 int what = message.what;
3264 // Prevent reads below from happening before the read from Message
3265 atomic_thread_fence(memory_order_acquire);
3266 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003267 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003268 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003269 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003270 exitRequested = true;
3271 }
3272 }
3273
3274public:
Jesse Hallb154c422014-07-13 12:47:02 -07003275 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3276 : impl(impl),
3277 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003278 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003279 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003280 exitRequested(false),
3281 code(0),
3282 data(NULL),
3283 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003284 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003285
Jesse Hallb154c422014-07-13 12:47:02 -07003286 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003287 status_t waitForResponse() {
3288 do {
3289 looper->pollOnce(-1);
3290 } while (!exitRequested);
3291 return result;
3292 }
3293
Jesse Hallb154c422014-07-13 12:47:02 -07003294 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003295 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003296 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003297 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003298 // Ensure this->result is visible to the binder thread before it
3299 // handles the message.
3300 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003301 looper->sendMessage(this, Message(MSG_EXIT));
3302 }
3303};
3304
3305
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003306status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3307 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003308 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003309 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003310 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003311
3312 if (CC_UNLIKELY(display == 0))
3313 return BAD_VALUE;
3314
3315 if (CC_UNLIKELY(producer == 0))
3316 return BAD_VALUE;
3317
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003318 // if we have secure windows on this display, never allow the screen capture
3319 // unless the producer interface is local (i.e.: we can take a screenshot for
3320 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003321 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003322
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003323 // Convert to surfaceflinger's internal rotation type.
3324 Transform::orientation_flags rotationFlags;
3325 switch (rotation) {
3326 case ISurfaceComposer::eRotateNone:
3327 rotationFlags = Transform::ROT_0;
3328 break;
3329 case ISurfaceComposer::eRotate90:
3330 rotationFlags = Transform::ROT_90;
3331 break;
3332 case ISurfaceComposer::eRotate180:
3333 rotationFlags = Transform::ROT_180;
3334 break;
3335 case ISurfaceComposer::eRotate270:
3336 rotationFlags = Transform::ROT_270;
3337 break;
3338 default:
3339 rotationFlags = Transform::ROT_0;
3340 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3341 break;
3342 }
3343
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003344 class MessageCaptureScreen : public MessageBase {
3345 SurfaceFlinger* flinger;
3346 sp<IBinder> display;
3347 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003348 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003349 uint32_t reqWidth, reqHeight;
3350 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003351 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003352 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003353 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003354 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003355 public:
3356 MessageCaptureScreen(SurfaceFlinger* flinger,
3357 const sp<IBinder>& display,
3358 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003359 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003360 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003361 bool useIdentityTransform,
3362 Transform::orientation_flags rotation,
3363 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003364 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003365 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003366 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003367 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003368 rotation(rotation), result(PERMISSION_DENIED),
3369 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003370 {
3371 }
3372 status_t getResult() const {
3373 return result;
3374 }
3375 virtual bool handler() {
3376 Mutex::Autolock _l(flinger->mStateLock);
3377 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003378 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003379 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003380 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003381 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003382 return true;
3383 }
3384 };
3385
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003386 // this creates a "fake" BBinder which will serve as a "fake" remote
3387 // binder to receive the marshaled calls and forward them to the
3388 // real remote (a BpGraphicBufferProducer)
3389 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3390
3391 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3392 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003393 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003394 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003395 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003396 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003397
3398 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003399 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003400 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003401 }
3402 return res;
3403}
3404
Mathias Agopian180f10d2013-04-10 22:55:41 -07003405
3406void SurfaceFlinger::renderScreenImplLocked(
3407 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003408 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003409 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003410 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003411{
3412 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003413 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003414
3415 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003416 const int32_t hw_w = hw->getWidth();
3417 const int32_t hw_h = hw->getHeight();
3418 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003419 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003420
Dan Stozac1879002014-05-22 15:59:05 -07003421 // if a default or invalid sourceCrop is passed in, set reasonable values
3422 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3423 !sourceCrop.isValid()) {
3424 sourceCrop.setLeftTop(Point(0, 0));
3425 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3426 }
3427
3428 // ensure that sourceCrop is inside screen
3429 if (sourceCrop.left < 0) {
3430 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3431 }
Dan Stozabe31f442014-06-11 11:20:54 -07003432 if (sourceCrop.right > hw_w) {
3433 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003434 }
3435 if (sourceCrop.top < 0) {
3436 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3437 }
Dan Stozabe31f442014-06-11 11:20:54 -07003438 if (sourceCrop.bottom > hw_h) {
3439 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003440 }
3441
Mathias Agopian180f10d2013-04-10 22:55:41 -07003442 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003443 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003444
3445 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003446 engine.setViewportAndProjection(
3447 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003448 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003449
3450 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003451 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003452
3453 const LayerVector& layers( mDrawingState.layersSortedByZ );
3454 const size_t count = layers.size();
3455 for (size_t i=0 ; i<count ; ++i) {
3456 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003457 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003458 if (state.layerStack == hw->getLayerStack()) {
3459 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3460 if (layer->isVisible()) {
3461 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003462 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003463 if (filtering) layer->setFiltering(false);
3464 }
3465 }
3466 }
3467 }
3468
Mathias Agopian931bda12013-08-28 18:11:46 -07003469 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003470}
3471
3472
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003473status_t SurfaceFlinger::captureScreenImplLocked(
3474 const sp<const DisplayDevice>& hw,
3475 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003476 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003477 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003478 bool useIdentityTransform, Transform::orientation_flags rotation,
3479 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003480{
3481 ATRACE_CALL();
3482
Mathias Agopian180f10d2013-04-10 22:55:41 -07003483 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003484 uint32_t hw_w = hw->getWidth();
3485 uint32_t hw_h = hw->getHeight();
3486
3487 if (rotation & Transform::ROT_90) {
3488 std::swap(hw_w, hw_h);
3489 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003490
Mathias Agopian180f10d2013-04-10 22:55:41 -07003491 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3492 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3493 reqWidth, reqHeight, hw_w, hw_h);
3494 return BAD_VALUE;
3495 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003496
Mathias Agopian180f10d2013-04-10 22:55:41 -07003497 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3498 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3499
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003500 bool secureLayerIsVisible = false;
3501 const LayerVector& layers(mDrawingState.layersSortedByZ);
3502 const size_t count = layers.size();
3503 for (size_t i = 0 ; i < count ; ++i) {
3504 const sp<Layer>& layer(layers[i]);
3505 const Layer::State& state(layer->getDrawingState());
3506 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3507 state.z <= maxLayerZ && layer->isVisible() &&
3508 layer->isSecure()) {
3509 secureLayerIsVisible = true;
3510 }
3511 }
3512
3513 if (!isLocalScreenshot && secureLayerIsVisible) {
3514 ALOGW("FB is protected: PERMISSION_DENIED");
3515 return PERMISSION_DENIED;
3516 }
3517
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003518 // create a surface (because we're a producer, and we need to
3519 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003520 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003521 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003522
Michael Lentine5a16a622015-05-21 13:48:24 -07003523 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3524 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003525 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3526 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003527
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003528 int err = 0;
3529 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003530 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003531 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3532 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003533
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003534 if (err == NO_ERROR) {
3535 ANativeWindowBuffer* buffer;
3536 /* TODO: Once we have the sync framework everywhere this can use
3537 * server-side waits on the fence that dequeueBuffer returns.
3538 */
3539 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3540 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003541 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003542 // create an EGLImage from the buffer so we can later
3543 // turn it into a texture
3544 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3545 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3546 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003547 // this binds the given EGLImage as a framebuffer for the
3548 // duration of this scope.
3549 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3550 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003551 // this will in fact render into our dequeued buffer
3552 // via an FBO, which means we didn't have to create
3553 // an EGLSurface and therefore we're not
3554 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003555 renderScreenImplLocked(
3556 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3557 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003558
Riley Andrews86639902014-08-15 12:27:24 -07003559 // Attempt to create a sync khr object that can produce a sync point. If that
3560 // isn't available, create a non-dupable sync object in the fallback path and
3561 // wait on it directly.
3562 EGLSyncKHR sync;
3563 if (!DEBUG_SCREENSHOTS) {
3564 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003565 // native fence fd will not be populated until flush() is done.
3566 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003567 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003568 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003569 }
Riley Andrews86639902014-08-15 12:27:24 -07003570 if (sync != EGL_NO_SYNC_KHR) {
3571 // get the sync fd
3572 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3573 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3574 ALOGW("captureScreen: failed to dup sync khr object");
3575 syncFd = -1;
3576 }
3577 eglDestroySyncKHR(mEGLDisplay, sync);
3578 } else {
3579 // fallback path
3580 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3581 if (sync != EGL_NO_SYNC_KHR) {
3582 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3583 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3584 EGLint eglErr = eglGetError();
3585 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3586 ALOGW("captureScreen: fence wait timed out");
3587 } else {
3588 ALOGW_IF(eglErr != EGL_SUCCESS,
3589 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3590 }
3591 eglDestroySyncKHR(mEGLDisplay, sync);
3592 } else {
3593 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3594 }
3595 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003596 if (DEBUG_SCREENSHOTS) {
3597 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3598 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3599 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3600 hw, minLayerZ, maxLayerZ);
3601 delete [] pixels;
3602 }
3603
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003604 } else {
3605 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3606 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003607 window->cancelBuffer(window, buffer, syncFd);
3608 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003609 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003610 // destroy our image
3611 eglDestroyImageKHR(mEGLDisplay, image);
3612 } else {
3613 result = BAD_VALUE;
3614 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003615 if (buffer) {
3616 // queueBuffer takes ownership of syncFd
3617 result = window->queueBuffer(window, buffer, syncFd);
3618 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003619 }
3620 } else {
3621 result = BAD_VALUE;
3622 }
3623 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3624 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003625
Mathias Agopian74c40c02010-09-29 13:02:36 -07003626 return result;
3627}
3628
Mathias Agopiand5556842013-09-19 17:08:37 -07003629void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3630 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003631 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003632 for (size_t y=0 ; y<h ; y++) {
3633 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3634 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003635 if (p[x] != 0xFF000000) return;
3636 }
3637 }
3638 ALOGE("*** we just took a black screenshot ***\n"
3639 "requested minz=%d, maxz=%d, layerStack=%d",
3640 minLayerZ, maxLayerZ, hw->getLayerStack());
3641 const LayerVector& layers( mDrawingState.layersSortedByZ );
3642 const size_t count = layers.size();
3643 for (size_t i=0 ; i<count ; ++i) {
3644 const sp<Layer>& layer(layers[i]);
3645 const Layer::State& state(layer->getDrawingState());
3646 const bool visible = (state.layerStack == hw->getLayerStack())
3647 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3648 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003649 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003650 visible ? '+' : '-',
3651 i, layer->getName().string(), state.layerStack, state.z,
3652 layer->isVisible(), state.flags, state.alpha);
3653 }
3654 }
3655}
3656
Pablo Ceballosce796e72016-02-04 19:10:51 -08003657bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3658 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3659 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3660}
3661
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003662// ---------------------------------------------------------------------------
3663
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003664SurfaceFlinger::LayerVector::LayerVector() {
3665}
3666
3667SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003668 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003669}
3670
3671int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3672 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003673{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003674 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003675 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3676 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003677
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003678 uint32_t ls = l->getCurrentState().layerStack;
3679 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003680 if (ls != rs)
3681 return ls - rs;
3682
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003683 uint32_t lz = l->getCurrentState().z;
3684 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003685 if (lz != rz)
3686 return lz - rz;
3687
3688 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003689}
3690
3691// ---------------------------------------------------------------------------
3692
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003693SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003694 : type(DisplayDevice::DISPLAY_ID_INVALID),
3695 layerStack(DisplayDevice::NO_LAYER_STACK),
3696 orientation(0),
3697 width(0),
3698 height(0),
3699 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003700}
3701
Pablo Ceballos53390e12015-08-04 11:25:59 -07003702SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3703 DisplayDevice::DisplayType type, bool isSecure)
3704 : type(type),
3705 layerStack(DisplayDevice::NO_LAYER_STACK),
3706 orientation(0),
3707 width(0),
3708 height(0),
3709 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003710 viewport.makeInvalid();
3711 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003712}
3713
3714// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003717
3718
3719#if defined(__gl_h_)
3720#error "don't include gl/gl.h in this file"
3721#endif
3722
3723#if defined(__gl2_h_)
3724#error "don't include gl2/gl2.h in this file"
3725#endif