blob: f298399ac5a0111911856b04308b625d31ea2105 [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");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182}
183
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800184void SurfaceFlinger::onFirstRef()
185{
186 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800187}
188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189SurfaceFlinger::~SurfaceFlinger()
190{
Mathias Agopiana4912602012-07-12 14:25:33 -0700191 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
192 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
193 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800194}
195
Dan Stozac7014012014-02-14 15:03:43 -0800196void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197{
198 // the window manager died on us. prepare its eulogy.
199
Andy McFadden13a082e2012-08-24 10:16:42 -0700200 // restore initial conditions (default device unblank, etc)
201 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800202
203 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700204 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205}
206
Mathias Agopian7e27f052010-05-28 14:22:23 -0700207sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208{
Mathias Agopian96f08192010-06-02 23:28:45 -0700209 sp<ISurfaceComposerClient> bclient;
210 sp<Client> client(new Client(this));
211 status_t err = client->initCheck();
212 if (err == NO_ERROR) {
213 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215 return bclient;
216}
217
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700218sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
219 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700220{
221 class DisplayToken : public BBinder {
222 sp<SurfaceFlinger> flinger;
223 virtual ~DisplayToken() {
224 // no more references, this display must be terminated
225 Mutex::Autolock _l(flinger->mStateLock);
226 flinger->mCurrentState.displays.removeItem(this);
227 flinger->setTransactionFlags(eDisplayTransactionNeeded);
228 }
229 public:
230 DisplayToken(const sp<SurfaceFlinger>& flinger)
231 : flinger(flinger) {
232 }
233 };
234
235 sp<BBinder> token = new DisplayToken(this);
236
237 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700238 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700239 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700240 mCurrentState.displays.add(token, info);
241
242 return token;
243}
244
Jesse Hall6c913be2013-08-08 12:15:49 -0700245void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
246 Mutex::Autolock _l(mStateLock);
247
248 ssize_t idx = mCurrentState.displays.indexOfKey(display);
249 if (idx < 0) {
250 ALOGW("destroyDisplay: invalid display token");
251 return;
252 }
253
254 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
255 if (!info.isVirtualDisplay()) {
256 ALOGE("destroyDisplay called for non-virtual display");
257 return;
258 }
259
260 mCurrentState.displays.removeItemsAt(idx);
261 setTransactionFlags(eDisplayTransactionNeeded);
262}
263
Jesse Hall692c7232012-11-08 15:41:56 -0800264void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800265 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800266 ALOGW_IF(mBuiltinDisplays[type],
267 "Overwriting display token for display type %d", type);
268 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800269 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700270 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800271 mCurrentState.displays.add(mBuiltinDisplays[type], info);
272}
273
Mathias Agopiane57f2922012-08-09 16:29:12 -0700274sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700275 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700276 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
277 return NULL;
278 }
Jesse Hall692c7232012-11-08 15:41:56 -0800279 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280}
281
Jamie Gennis9a78c902011-01-12 18:30:40 -0800282sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
283{
284 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
285 return gba;
286}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288void SurfaceFlinger::bootFinished()
289{
290 const nsecs_t now = systemTime();
291 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000292 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700293 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700294
295 // wait patiently for the window manager death
296 const String16 name("window");
297 sp<IBinder> window(defaultServiceManager()->getService(name));
298 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700299 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700300 }
301
302 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700303 // formerly we would just kill the process, but we now ask it to exit so it
304 // can choose where to stop the animation.
305 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700306
307 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
308 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
309 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310}
311
Mathias Agopian3f844832013-08-07 21:24:32 -0700312void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700313 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700314 RenderEngine& engine;
315 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700316 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700317 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
318 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700319 }
320 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700321 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700322 return true;
323 }
324 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700325 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700326}
327
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700328class DispSyncSource : public VSyncSource, private DispSync::Callback {
329public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700330 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000331 const char* name) :
332 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700333 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700334 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000335 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
336 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700337 mDispSync(dispSync),
338 mCallbackMutex(),
339 mCallback(),
340 mVsyncMutex(),
341 mPhaseOffset(phaseOffset),
342 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700343
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700344 virtual ~DispSyncSource() {}
345
346 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700347 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700348 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000349 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700350 static_cast<DispSync::Callback*>(this));
351 if (err != NO_ERROR) {
352 ALOGE("error registering vsync callback: %s (%d)",
353 strerror(-err), err);
354 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700355 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700356 } else {
357 status_t err = mDispSync->removeEventListener(
358 static_cast<DispSync::Callback*>(this));
359 if (err != NO_ERROR) {
360 ALOGE("error unregistering vsync callback: %s (%d)",
361 strerror(-err), err);
362 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700363 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700364 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700365 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700366 }
367
368 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700369 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700370 mCallback = callback;
371 }
372
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700373 virtual void setPhaseOffset(nsecs_t phaseOffset) {
374 Mutex::Autolock lock(mVsyncMutex);
375
376 // Normalize phaseOffset to [0, period)
377 auto period = mDispSync->getPeriod();
378 phaseOffset %= period;
379 if (phaseOffset < 0) {
380 // If we're here, then phaseOffset is in (-period, 0). After this
381 // operation, it will be in (0, period)
382 phaseOffset += period;
383 }
384 mPhaseOffset = phaseOffset;
385
386 // If we're not enabled, we don't need to mess with the listeners
387 if (!mEnabled) {
388 return;
389 }
390
391 // Remove the listener with the old offset
392 status_t err = mDispSync->removeEventListener(
393 static_cast<DispSync::Callback*>(this));
394 if (err != NO_ERROR) {
395 ALOGE("error unregistering vsync callback: %s (%d)",
396 strerror(-err), err);
397 }
398
399 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000400 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700401 static_cast<DispSync::Callback*>(this));
402 if (err != NO_ERROR) {
403 ALOGE("error registering vsync callback: %s (%d)",
404 strerror(-err), err);
405 }
406 }
407
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700408private:
409 virtual void onDispSyncEvent(nsecs_t when) {
410 sp<VSyncSource::Callback> callback;
411 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700413 callback = mCallback;
414
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700415 if (mTraceVsync) {
416 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700417 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700418 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700419 }
420
421 if (callback != NULL) {
422 callback->onVSyncEvent(when);
423 }
424 }
425
Tim Murray4a4e4a22016-04-19 16:29:23 +0000426 const char* const mName;
427
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 int mValue;
429
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700430 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700431 const String8 mVsyncOnLabel;
432 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700433
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435
436 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438
439 Mutex mVsyncMutex; // Protects the following
440 nsecs_t mPhaseOffset;
441 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442};
443
444void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700445 ALOGI( "SurfaceFlinger's main thread ready to run. "
446 "Initializing graphics H/W...");
447
Dan Stoza9e56aa02015-11-02 13:00:03 -0800448 { // Autolock scope
449 Mutex::Autolock _l(mStateLock);
450
451 // initialize EGL for the default display
452 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
453 eglInitialize(mEGLDisplay, NULL, NULL);
454
455 // start the EventThread
456 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
457 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000458 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800459 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
460 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000461 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800462 mEventQueue.setEventThread(mSFEventThread);
463
Tim Murray41a38532016-06-22 12:42:10 -0700464 // set EventThread and SFEventThread to SCHED_FIFO for minimum jitter
465 struct sched_param param = {0};
466 param.sched_priority = 1;
467 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
468 ALOGE("Couldn't set SCHED_FIFO for EventThread");
469 }
470
471 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
472 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
473 }
474
475
Dan Stoza9e56aa02015-11-02 13:00:03 -0800476 // Get a RenderEngine for the given display / config (can't fail)
477 mRenderEngine = RenderEngine::create(mEGLDisplay,
478 HAL_PIXEL_FORMAT_RGBA_8888);
479 }
480
481 // Drop the state lock while we initialize the hardware composer. We drop
482 // the lock because on creation, it will call back into SurfaceFlinger to
483 // initialize the primary display.
484 mHwc = new HWComposer(this);
485 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
486
Jesse Hall692c7232012-11-08 15:41:56 -0800487 Mutex::Autolock _l(mStateLock);
488
Mathias Agopian875d8e12013-06-07 15:35:48 -0700489 // retrieve the EGL context that was selected/created
490 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700491
Mathias Agopianda27af92012-09-13 18:17:13 -0700492 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
493 "couldn't create EGLContext");
494
Dan Stoza9e56aa02015-11-02 13:00:03 -0800495 // make the GLContext current so that we can create textures when creating
496 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700497 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
498
Jamie Gennisd1700752013-10-14 12:22:52 -0700499 mEventControlThread = new EventControlThread(this);
500 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
501
Mathias Agopian92a979a2012-08-02 18:32:23 -0700502 // initialize our drawing state
503 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700504
Andy McFadden13a082e2012-08-24 10:16:42 -0700505 // set initial conditions (e.g. unblank default device)
506 initializeDisplays();
507
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700508 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700509 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800510
Dan Stoza9e56aa02015-11-02 13:00:03 -0800511 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700512}
513
Mathias Agopiana67e4182012-06-19 17:26:12 -0700514void SurfaceFlinger::startBootAnim() {
515 // start boot animation
516 property_set("service.bootanim.exit", "0");
517 property_set("ctl.start", "bootanim");
518}
519
Mathias Agopian875d8e12013-06-07 15:35:48 -0700520size_t SurfaceFlinger::getMaxTextureSize() const {
521 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700522}
523
Mathias Agopian875d8e12013-06-07 15:35:48 -0700524size_t SurfaceFlinger::getMaxViewportDims() const {
525 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700526}
527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800529
Jamie Gennis582270d2011-08-17 18:19:00 -0700530bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800531 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800532 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800533 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700534 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800535}
536
Dan Stoza7f7da322014-05-02 15:26:25 -0700537status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
538 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700539 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700540 return BAD_VALUE;
541 }
542
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500543 if (!display.get())
544 return NAME_NOT_FOUND;
545
Jesse Hall692c7232012-11-08 15:41:56 -0800546 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700547 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800548 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700549 type = i;
550 break;
551 }
552 }
553
554 if (type < 0) {
555 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700556 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700557
Mathias Agopian8b736f12012-08-13 17:54:26 -0700558 // TODO: Not sure if display density should handled by SF any longer
559 class Density {
560 static int getDensityFromProperty(char const* propName) {
561 char property[PROPERTY_VALUE_MAX];
562 int density = 0;
563 if (property_get(propName, property, NULL) > 0) {
564 density = atoi(property);
565 }
566 return density;
567 }
568 public:
569 static int getEmuDensity() {
570 return getDensityFromProperty("qemu.sf.lcd_density"); }
571 static int getBuildDensity() {
572 return getDensityFromProperty("ro.sf.lcd_density"); }
573 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700574
Dan Stoza7f7da322014-05-02 15:26:25 -0700575 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700576
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700578 DisplayInfo info = DisplayInfo();
579
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580 float xdpi = hwConfig->getDpiX();
581 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700582
583 if (type == DisplayDevice::DISPLAY_PRIMARY) {
584 // The density of the device is provided by a build property
585 float density = Density::getBuildDensity() / 160.0f;
586 if (density == 0) {
587 // the build doesn't provide a density -- this is wrong!
588 // use xdpi instead
589 ALOGE("ro.sf.lcd_density must be defined as a build property");
590 density = xdpi / 160.0f;
591 }
592 if (Density::getEmuDensity()) {
593 // if "qemu.sf.lcd_density" is specified, it overrides everything
594 xdpi = ydpi = density = Density::getEmuDensity();
595 density /= 160.0f;
596 }
597 info.density = density;
598
599 // TODO: this needs to go away (currently needed only by webkit)
600 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
601 info.orientation = hw->getOrientation();
602 } else {
603 // TODO: where should this value come from?
604 static const int TV_DENSITY = 213;
605 info.density = TV_DENSITY / 160.0f;
606 info.orientation = 0;
607 }
608
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 info.w = hwConfig->getWidth();
610 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700611 info.xdpi = xdpi;
612 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800613 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700614 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800615
Andy McFadden91b2ca82014-06-13 14:04:23 -0700616 // This is how far in advance a buffer must be queued for
617 // presentation at a given time. If you want a buffer to appear
618 // on the screen at time N, you must submit the buffer before
619 // (N - presentationDeadline).
620 //
621 // Normally it's one full refresh period (to give SF a chance to
622 // latch the buffer), but this can be reduced by configuring a
623 // DispSync offset. Any additional delays introduced by the hardware
624 // composer or panel must be accounted for here.
625 //
626 // We add an additional 1ms to allow for processing time and
627 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800628 info.presentationDeadline = hwConfig->getVsyncPeriod() -
629 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700630
631 // All non-virtual displays are currently considered secure.
632 info.secure = true;
633
Courtney Goeltzenleuchterfad9d8c2016-06-23 11:49:50 -0600634 // DisplayManager expects each color mode to be its own display
635 // info record.
636 std::vector<int32_t> modes = getHwComposer().getColorModes(type);
637
638 if (modes.size() == 0) {
639 info.colorTransform = 0;
640 configs->push_back(info);
641 }
642 for (int32_t mode : modes) {
643 info.colorTransform = mode;
644 configs->push_back(info);
645 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700646 }
647
Dan Stoza7f7da322014-05-02 15:26:25 -0700648 return NO_ERROR;
649}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700650
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800651status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700652 DisplayStatInfo* stats) {
653 if (stats == NULL) {
654 return BAD_VALUE;
655 }
656
657 // FIXME for now we always return stats for the primary display
658 memset(stats, 0, sizeof(*stats));
659 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
660 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
661 return NO_ERROR;
662}
663
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700664int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700665 sp<DisplayDevice> device(getDisplayDevice(display));
666 if (device != NULL) {
667 return device->getActiveConfig();
668 }
669 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700670}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700671
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700672void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
673 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
674 this);
675 int32_t type = hw->getDisplayType();
676 int currentMode = hw->getActiveConfig();
677
678 if (mode == currentMode) {
679 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
680 return;
681 }
682
683 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
684 ALOGW("Trying to set config for virtual display");
685 return;
686 }
687
688 hw->setActiveConfig(mode);
689 getHwComposer().setActiveConfig(type, mode);
690}
691
692status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
693 class MessageSetActiveConfig: public MessageBase {
694 SurfaceFlinger& mFlinger;
695 sp<IBinder> mDisplay;
696 int mMode;
697 public:
698 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
699 int mode) :
700 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
701 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700702 Vector<DisplayInfo> configs;
703 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700704 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700705 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700706 mMode, configs.size());
707 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700708 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
709 if (hw == NULL) {
710 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700711 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700712 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
713 ALOGW("Attempt to set active config = %d for virtual display",
714 mMode);
715 } else {
716 mFlinger.setActiveConfigInternal(hw, mMode);
717 }
718 return true;
719 }
720 };
721 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
722 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700723 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700724}
725
Svetoslavd85084b2014-03-20 10:28:31 -0700726status_t SurfaceFlinger::clearAnimationFrameStats() {
727 Mutex::Autolock _l(mStateLock);
728 mAnimFrameTracker.clearStats();
729 return NO_ERROR;
730}
731
732status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
733 Mutex::Autolock _l(mStateLock);
734 mAnimFrameTracker.getStats(outStats);
735 return NO_ERROR;
736}
737
Dan Stozac4f471e2016-03-24 09:31:08 -0700738status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
739 HdrCapabilities* outCapabilities) const {
740 Mutex::Autolock _l(mStateLock);
741
742 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
743 if (displayDevice == nullptr) {
744 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
745 return BAD_VALUE;
746 }
747
748 std::unique_ptr<HdrCapabilities> capabilities =
749 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
750 if (capabilities) {
751 std::swap(*outCapabilities, *capabilities);
752 } else {
753 return BAD_VALUE;
754 }
755
756 return NO_ERROR;
757}
758
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800759// ----------------------------------------------------------------------------
760
761sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800762 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700763}
764
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800765// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800766
767void SurfaceFlinger::waitForEvent() {
768 mEventQueue.waitMessage();
769}
770
771void SurfaceFlinger::signalTransaction() {
772 mEventQueue.invalidate();
773}
774
775void SurfaceFlinger::signalLayerUpdate() {
776 mEventQueue.invalidate();
777}
778
779void SurfaceFlinger::signalRefresh() {
780 mEventQueue.refresh();
781}
782
783status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800784 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800785 return mEventQueue.postMessage(msg, reltime);
786}
787
788status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800789 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800790 status_t res = mEventQueue.postMessage(msg, reltime);
791 if (res == NO_ERROR) {
792 msg->wait();
793 }
794 return res;
795}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800796
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700797void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700798 do {
799 waitForEvent();
800 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801}
802
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700803void SurfaceFlinger::enableHardwareVsync() {
804 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700805 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700806 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700807 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
808 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700809 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700810 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700811}
812
Jesse Hall948fe0c2013-10-14 12:56:09 -0700813void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700814 Mutex::Autolock _l(mHWVsyncLock);
815
Jesse Hall948fe0c2013-10-14 12:56:09 -0700816 if (makeAvailable) {
817 mHWVsyncAvailable = true;
818 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700819 // Hardware vsync is not currently available, so abort the resync
820 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700821 return;
822 }
823
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
825 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700826
827 mPrimaryDispSync.reset();
828 mPrimaryDispSync.setPeriod(period);
829
830 if (!mPrimaryHWVsyncEnabled) {
831 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700832 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
833 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700834 mPrimaryHWVsyncEnabled = true;
835 }
836}
837
Jesse Hall948fe0c2013-10-14 12:56:09 -0700838void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700839 Mutex::Autolock _l(mHWVsyncLock);
840 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700841 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
842 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700843 mPrimaryDispSync.endResync();
844 mPrimaryHWVsyncEnabled = false;
845 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700846 if (makeUnavailable) {
847 mHWVsyncAvailable = false;
848 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700849}
850
Tim Murray4a4e4a22016-04-19 16:29:23 +0000851void SurfaceFlinger::resyncWithRateLimit() {
852 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
853 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700854 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000855 }
856}
857
Dan Stoza9e56aa02015-11-02 13:00:03 -0800858void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700859 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700860
Jamie Gennisd1700752013-10-14 12:22:52 -0700861 { // Scope for the lock
862 Mutex::Autolock _l(mHWVsyncLock);
863 if (type == 0 && mPrimaryHWVsyncEnabled) {
864 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700865 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700866 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700867
868 if (needsHwVsync) {
869 enableHardwareVsync();
870 } else {
871 disableHardwareVsync(false);
872 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700873}
874
Dan Stoza9e56aa02015-11-02 13:00:03 -0800875void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
876 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
877 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
878 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700879
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880 // All non-virtual displays are currently considered secure.
881 bool isSecure = true;
882
883 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
884 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
885 wp<IBinder> token = mBuiltinDisplays[type];
886
887 sp<IGraphicBufferProducer> producer;
888 sp<IGraphicBufferConsumer> consumer;
889 BufferQueue::createBufferQueue(&producer, &consumer,
890 new GraphicBufferAlloc());
891
892 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
893 DisplayDevice::DISPLAY_PRIMARY, consumer);
894 sp<DisplayDevice> hw = new DisplayDevice(this,
895 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
896 producer, mRenderEngine->getEGLConfig());
897 mDisplays.add(token, hw);
898 } else {
899 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700900 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800901 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700903 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800904 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
905 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700906 }
907 setTransactionFlags(eDisplayTransactionNeeded);
908
Andy McFadden9e9689c2012-10-10 18:17:51 -0700909 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700910 }
Mathias Agopian86303202012-07-24 22:46:10 -0700911}
912
Dan Stoza9e56aa02015-11-02 13:00:03 -0800913void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700914 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800915 getHwComposer().setVsyncEnabled(disp,
916 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700917}
918
Mathias Agopian4fec8732012-06-29 14:12:52 -0700919void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800920 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800921 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800922 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -0700923 bool frameMissed = !mHadClientComposition &&
924 mPreviousPresentFence != Fence::NO_FENCE &&
925 mPreviousPresentFence->getSignalTime() == INT64_MAX;
926 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
927 if (frameMissed) {
928 signalLayerUpdate();
929 break;
930 }
931
Dan Stoza6b9454d2014-11-07 16:00:59 -0800932 bool refreshNeeded = handleMessageTransaction();
933 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800934 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800935 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800936 // Signal a refresh if a transaction modified the window state,
937 // a new buffer was latched, or if HWC has requested a full
938 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800939 signalRefresh();
940 }
941 break;
942 }
943 case MessageQueue::REFRESH: {
944 handleMessageRefresh();
945 break;
946 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800947 }
948}
949
Dan Stoza6b9454d2014-11-07 16:00:59 -0800950bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700951 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700952 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700953 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800954 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700955 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800956 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700957}
958
Dan Stoza6b9454d2014-11-07 16:00:59 -0800959bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700960 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800961 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700962}
963
964void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700965 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700966
Pablo Ceballos40845df2016-01-25 17:41:15 -0800967 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700968
Dan Stoza05dacfb2016-07-01 13:33:38 -0700969 preComposition();
970 rebuildLayerStacks();
971 setUpHWComposer();
972 doDebugFlashRegions();
973 doComposition();
974 postComposition(refreshStartTime);
975
976 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
977 mHadClientComposition = mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700978
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979 // Release any buffers which were replaced this frame
980 for (auto& layer : mLayersWithQueuedFrames) {
981 layer->releasePendingBuffer();
982 }
983 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700984}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700985
Mathias Agopiancd60f992012-08-16 16:28:27 -0700986void SurfaceFlinger::doDebugFlashRegions()
987{
988 // is debugging enabled
989 if (CC_LIKELY(!mDebugRegion))
990 return;
991
992 const bool repaintEverything = mRepaintEverything;
993 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
994 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -0700995 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700996 // transform the dirty region into this screen's coordinate space
997 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
998 if (!dirtyRegion.isEmpty()) {
999 // redraw the whole screen
1000 doComposeSurfaces(hw, Region(hw->bounds()));
1001
1002 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001003 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001004 RenderEngine& engine(getRenderEngine());
1005 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1006
Mathias Agopianda27af92012-09-13 18:17:13 -07001007 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001008 }
1009 }
1010 }
1011
1012 postFramebuffer();
1013
1014 if (mDebugRegion > 1) {
1015 usleep(mDebugRegion * 1000);
1016 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001017
Dan Stoza9e56aa02015-11-02 13:00:03 -08001018 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001019 auto& displayDevice = mDisplays[displayId];
1020 if (!displayDevice->isDisplayOn()) {
1021 continue;
1022 }
1023
1024 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001025 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1026 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001027 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001028}
1029
1030void SurfaceFlinger::preComposition()
1031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001032 ATRACE_CALL();
1033 ALOGV("preComposition");
1034
Mathias Agopiancd60f992012-08-16 16:28:27 -07001035 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001036 const LayerVector& layers(mDrawingState.layersSortedByZ);
1037 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001038 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001039 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001040 needExtraInvalidate = true;
1041 }
1042 }
1043 if (needExtraInvalidate) {
1044 signalLayerUpdate();
1045 }
1046}
1047
Pablo Ceballos40845df2016-01-25 17:41:15 -08001048void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001049{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001050 ATRACE_CALL();
1051 ALOGV("postComposition");
1052
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001053 const LayerVector& layers(mDrawingState.layersSortedByZ);
1054 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001055 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001056 bool frameLatched = layers[i]->onPostComposition();
1057 if (frameLatched) {
1058 recordBufferingStats(layers[i]->getName().string(),
1059 layers[i]->getOccupancyHistory(false));
1060 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001061 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001062
Dan Stoza9e56aa02015-11-02 13:00:03 -08001063 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001064
1065 if (presentFence->isValid()) {
1066 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1067 enableHardwareVsync();
1068 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001069 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070 }
1071 }
1072
Dan Stozab90cf072015-03-05 11:05:59 -08001073 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001074 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001075 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 enableHardwareVsync();
1077 }
1078 }
1079
Pablo Ceballos40845df2016-01-25 17:41:15 -08001080 mFenceTracker.addFrame(refreshStartTime, presentFence,
1081 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1082
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001083 if (mAnimCompositionPending) {
1084 mAnimCompositionPending = false;
1085
Jesse Halla9a1b002013-02-27 16:39:25 -08001086 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001087 mAnimFrameTracker.setActualPresentFence(presentFence);
1088 } else {
1089 // The HWC doesn't support present fences, so use the refresh
1090 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001091 nsecs_t presentTime =
1092 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001093 mAnimFrameTracker.setActualPresentTime(presentTime);
1094 }
1095 mAnimFrameTracker.advanceFrame();
1096 }
Dan Stozab90cf072015-03-05 11:05:59 -08001097
1098 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1099 return;
1100 }
1101
1102 nsecs_t currentTime = systemTime();
1103 if (mHasPoweredOff) {
1104 mHasPoweredOff = false;
1105 } else {
1106 nsecs_t period = mPrimaryDispSync.getPeriod();
1107 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1108 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1109 if (numPeriods < NUM_BUCKETS - 1) {
1110 mFrameBuckets[numPeriods] += elapsedTime;
1111 } else {
1112 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1113 }
1114 mTotalTime += elapsedTime;
1115 }
1116 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001117}
1118
1119void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001120 ATRACE_CALL();
1121 ALOGV("rebuildLayerStacks");
1122
Mathias Agopiancd60f992012-08-16 16:28:27 -07001123 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001124 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001125 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001126 mVisibleRegionsDirty = false;
1127 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001128
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001129 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001130 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001131 Region opaqueRegion;
1132 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001133 Vector<sp<Layer>> layersSortedByZ;
1134 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1135 const Transform& tr(displayDevice->getTransform());
1136 const Rect bounds(displayDevice->getBounds());
1137 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001138 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001139 displayDevice->getLayerStack(), dirtyRegion,
1140 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001141
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001142 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001143 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001144 const sp<Layer>& layer(layers[i]);
1145 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001146 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001147 Region drawRegion(tr.transform(
1148 layer->visibleNonTransparentRegion));
1149 drawRegion.andSelf(bounds);
1150 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001151 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001152 } else {
1153 // Clear out the HWC layer if this layer was
1154 // previously visible, but no longer is
1155 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1156 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001157 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001158 }
1159 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001160 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001161 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1162 displayDevice->undefinedRegion.set(bounds);
1163 displayDevice->undefinedRegion.subtractSelf(
1164 tr.transform(opaqueRegion));
1165 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001166 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001167 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001168}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001169
Mathias Agopiancd60f992012-08-16 16:28:27 -07001170void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001171 ATRACE_CALL();
1172 ALOGV("setUpHWComposer");
1173
Jesse Hall028dc8f2013-08-20 16:35:32 -07001174 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001175 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1176 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1177 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1178
1179 // If nothing has changed (!dirty), don't recompose.
1180 // If something changed, but we don't currently have any visible layers,
1181 // and didn't when we last did a composition, then skip it this time.
1182 // The second rule does two things:
1183 // - When all layers are removed from a display, we'll emit one black
1184 // frame, then nothing more until we get new layers.
1185 // - When a display is created with a private layer stack, we won't
1186 // emit any black frames until a layer is added to the layer stack.
1187 bool mustRecompose = dirty && !(empty && wasEmpty);
1188
1189 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1190 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1191 mustRecompose ? "doing" : "skipping",
1192 dirty ? "+" : "-",
1193 empty ? "+" : "-",
1194 wasEmpty ? "+" : "-");
1195
Dan Stoza71433162014-02-04 16:22:36 -08001196 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001197
1198 if (mustRecompose) {
1199 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1200 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001201 }
1202
Dan Stoza9e56aa02015-11-02 13:00:03 -08001203 // build the h/w work list
1204 if (CC_UNLIKELY(mGeometryInvalid)) {
1205 mGeometryInvalid = false;
1206 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1207 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1208 const auto hwcId = displayDevice->getHwcDisplayId();
1209 if (hwcId >= 0) {
1210 const Vector<sp<Layer>>& currentLayers(
1211 displayDevice->getVisibleLayersSortedByZ());
1212 bool foundLayerWithoutHwc = false;
1213 for (auto& layer : currentLayers) {
1214 if (!layer->hasHwcLayer(hwcId)) {
1215 auto hwcLayer = mHwc->createLayer(hwcId);
1216 if (hwcLayer) {
1217 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1218 } else {
1219 layer->forceClientComposition(hwcId);
1220 foundLayerWithoutHwc = true;
1221 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001222 }
1223 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001224
Dan Stoza9e56aa02015-11-02 13:00:03 -08001225 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001226 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001227 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001228 }
1229 }
1230 }
1231 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001232 }
Riley Andrews03414a12014-07-01 14:22:59 -07001233
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001234
1235 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1236
Dan Stoza9e56aa02015-11-02 13:00:03 -08001237 // Set the per-frame data
1238 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1239 auto& displayDevice = mDisplays[displayId];
1240 const auto hwcId = displayDevice->getHwcDisplayId();
1241 if (hwcId < 0) {
1242 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001243 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001244 if (colorMatrix != mPreviousColorMatrix) {
1245 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1246 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1247 "display %zd: %d", displayId, result);
1248 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001249 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1250 layer->setPerFrameData(displayDevice);
1251 }
1252 }
1253
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001254 mPreviousColorMatrix = colorMatrix;
1255
Dan Stoza9e56aa02015-11-02 13:00:03 -08001256 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001257 auto& displayDevice = mDisplays[displayId];
1258 if (!displayDevice->isDisplayOn()) {
1259 continue;
1260 }
1261
1262 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001263 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1264 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001265 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001266}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001267
Mathias Agopiancd60f992012-08-16 16:28:27 -07001268void SurfaceFlinger::doComposition() {
1269 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270 ALOGV("doComposition");
1271
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001272 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001273 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001274 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001275 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001276 // transform the dirty region into this screen's coordinate space
1277 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001278
1279 // repaint the framebuffer (if needed)
1280 doDisplayComposition(hw, dirtyRegion);
1281
Mathias Agopiancd60f992012-08-16 16:28:27 -07001282 hw->dirtyRegion.clear();
1283 hw->flip(hw->swapRegion);
1284 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001285 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001286 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001287 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001288}
1289
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001290void SurfaceFlinger::postFramebuffer()
1291{
Mathias Agopian841cde52012-03-01 15:44:37 -08001292 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001294
Mathias Agopiana44b0412011-10-16 18:46:35 -07001295 const nsecs_t now = systemTime();
1296 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001297
Dan Stoza9e56aa02015-11-02 13:00:03 -08001298 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1299 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001300 if (!displayDevice->isDisplayOn()) {
1301 continue;
1302 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 const auto hwcId = displayDevice->getHwcDisplayId();
1304 if (hwcId >= 0) {
1305 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001306 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001307 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 if (displayId == 0) {
1309 // Make the default display current because the VirtualDisplayDevice
1310 // code cannot deal with dequeueBuffer() being called outside of the
1311 // composition loop; however the code below can call glFlush() which
1312 // is allowed to (and does in some case) call dequeueBuffer().
1313 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1314 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001315 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1316 sp<Fence> releaseFence = Fence::NO_FENCE;
1317 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1318 releaseFence = displayDevice->getClientTargetAcquireFence();
1319 } else {
1320 auto hwcLayer = layer->getHwcLayer(hwcId);
1321 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001322 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001323 layer->onLayerDisplayed(releaseFence);
1324 }
1325 if (hwcId >= 0) {
1326 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001327 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001328 }
1329
Mathias Agopiana44b0412011-10-16 18:46:35 -07001330 mLastSwapBufferTime = systemTime() - now;
1331 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001332
1333 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1334 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1335 logFrameStats();
1336 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001337}
1338
Mathias Agopian87baae12012-07-31 12:38:26 -07001339void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001340{
Mathias Agopian841cde52012-03-01 15:44:37 -08001341 ATRACE_CALL();
1342
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001343 // here we keep a copy of the drawing state (that is the state that's
1344 // going to be overwritten by handleTransactionLocked()) outside of
1345 // mStateLock so that the side-effects of the State assignment
1346 // don't happen with mStateLock held (which can cause deadlocks).
1347 State drawingState(mDrawingState);
1348
Mathias Agopianca4d3602011-05-19 15:38:14 -07001349 Mutex::Autolock _l(mStateLock);
1350 const nsecs_t now = systemTime();
1351 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001352
Mathias Agopianca4d3602011-05-19 15:38:14 -07001353 // Here we're guaranteed that some transaction flags are set
1354 // so we can call handleTransactionLocked() unconditionally.
1355 // We call getTransactionFlags(), which will also clear the flags,
1356 // with mStateLock held to guarantee that mCurrentState won't change
1357 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001358
Mathias Agopiane57f2922012-08-09 16:29:12 -07001359 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001360 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001361
Mathias Agopianca4d3602011-05-19 15:38:14 -07001362 mLastTransactionTime = systemTime() - now;
1363 mDebugInTransaction = 0;
1364 invalidateHwcGeometry();
1365 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001366}
1367
Mathias Agopian87baae12012-07-31 12:38:26 -07001368void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001369{
1370 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001371 const size_t count = currentLayers.size();
1372
Dan Stoza7dde5992015-05-22 09:51:44 -07001373 // Notify all layers of available frames
1374 for (size_t i = 0; i < count; ++i) {
1375 currentLayers[i]->notifyAvailableFrames();
1376 }
1377
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001378 /*
1379 * Traversal of the children
1380 * (perform the transaction for each of them if needed)
1381 */
1382
Mathias Agopian3559b072012-08-15 13:46:03 -07001383 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001385 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001386 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1387 if (!trFlags) continue;
1388
1389 const uint32_t flags = layer->doTransaction(0);
1390 if (flags & Layer::eVisibleRegion)
1391 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001392 }
1393 }
1394
1395 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001396 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397 */
1398
Mathias Agopiane57f2922012-08-09 16:29:12 -07001399 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001400 // here we take advantage of Vector's copy-on-write semantics to
1401 // improve performance by skipping the transaction entirely when
1402 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001403 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1404 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001405 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001406 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001407 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001408 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001409
1410 // find the displays that were removed
1411 // (ie: in drawing state but not in current state)
1412 // also handle displays that changed
1413 // (ie: displays that are in both lists)
1414 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001415 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1416 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001417 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001418 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001419 // Call makeCurrent() on the primary display so we can
1420 // be sure that nothing associated with this display
1421 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001422 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001423 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001424 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1425 if (hw != NULL)
1426 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001427 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001428 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001429 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001430 } else {
1431 ALOGW("trying to remove the main display");
1432 }
1433 } else {
1434 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001435 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001436 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001437 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1438 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001439 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001440 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001441 // recreating the DisplayDevice, so we just remove it
1442 // from the drawing state, so that it get re-added
1443 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001444 sp<DisplayDevice> hw(getDisplayDevice(display));
1445 if (hw != NULL)
1446 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001447 mDisplays.removeItem(display);
1448 mDrawingState.displays.removeItemsAt(i);
1449 dc--; i--;
1450 // at this point we must loop to the next item
1451 continue;
1452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001453
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001454 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001455 if (disp != NULL) {
1456 if (state.layerStack != draw[i].layerStack) {
1457 disp->setLayerStack(state.layerStack);
1458 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001459 if ((state.orientation != draw[i].orientation)
1460 || (state.viewport != draw[i].viewport)
1461 || (state.frame != draw[i].frame))
1462 {
1463 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001464 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001465 }
Michael Lentine47e45402014-07-18 15:34:25 -07001466 if (state.width != draw[i].width || state.height != draw[i].height) {
1467 disp->setDisplaySize(state.width, state.height);
1468 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001469 }
1470 }
1471 }
1472
1473 // find displays that were added
1474 // (ie: in current state but not in drawing state)
1475 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001476 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001477 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001478
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001479 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001480 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001481 sp<IGraphicBufferProducer> bqProducer;
1482 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001483 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1484 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001485
Dan Stoza9e56aa02015-11-02 13:00:03 -08001486 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001487 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001488 // Virtual displays without a surface are dormant:
1489 // they have external state (layer stack, projection,
1490 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001491 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001492
Dan Stoza1f3efb12014-10-15 16:34:55 -07001493 int width = 0;
1494 int status = state.surface->query(
1495 NATIVE_WINDOW_WIDTH, &width);
1496 ALOGE_IF(status != NO_ERROR,
1497 "Unable to query width (%d)", status);
1498 int height = 0;
1499 status = state.surface->query(
1500 NATIVE_WINDOW_HEIGHT, &height);
1501 ALOGE_IF(status != NO_ERROR,
1502 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001503 int intFormat = 0;
1504 status = state.surface->query(
1505 NATIVE_WINDOW_FORMAT, &intFormat);
1506 ALOGE_IF(status != NO_ERROR,
1507 "Unable to query format (%d)", status);
1508 auto format = static_cast<android_pixel_format_t>(
1509 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001510
Dan Stoza5cf424b2016-05-20 14:02:39 -07001511 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001512 &hwcId);
1513
Dan Stoza5cf424b2016-05-20 14:02:39 -07001514 // TODO: Plumb requested format back up to consumer
1515
Dan Stoza9e56aa02015-11-02 13:00:03 -08001516 sp<VirtualDisplaySurface> vds =
1517 new VirtualDisplaySurface(*mHwc,
1518 hwcId, state.surface, bqProducer,
1519 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001520
1521 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001522 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001523 }
1524 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001525 ALOGE_IF(state.surface!=NULL,
1526 "adding a supported display, but rendering "
1527 "surface is provided (%p), ignoring it",
1528 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1530 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1531 dispSurface = new FramebufferSurface(*mHwc,
1532 DisplayDevice::DISPLAY_EXTERNAL,
1533 bqConsumer);
1534 producer = bqProducer;
1535 } else {
1536 ALOGE("Attempted to add non-external non-virtual"
1537 " display");
1538 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001539 }
1540
1541 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001542 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001543 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001544 state.type, hwcId, state.isSecure, display,
1545 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001546 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001547 hw->setLayerStack(state.layerStack);
1548 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001549 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001550 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001551 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001552 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001553 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001554 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001555 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001556 }
1557 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001558 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001559 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001560
Mathias Agopian84300952012-11-21 16:02:13 -08001561 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1562 // The transform hint might have changed for some layers
1563 // (either because a display has changed, or because a layer
1564 // as changed).
1565 //
1566 // Walk through all the layers in currentLayers,
1567 // and update their transform hint.
1568 //
1569 // If a layer is visible only on a single display, then that
1570 // display is used to calculate the hint, otherwise we use the
1571 // default display.
1572 //
1573 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1574 // the hint is set before we acquire a buffer from the surface texture.
1575 //
1576 // NOTE: layer transactions have taken place already, so we use their
1577 // drawing state. However, SurfaceFlinger's own transaction has not
1578 // happened yet, so we must use the current state layer list
1579 // (soon to become the drawing state list).
1580 //
1581 sp<const DisplayDevice> disp;
1582 uint32_t currentlayerStack = 0;
1583 for (size_t i=0; i<count; i++) {
1584 // NOTE: we rely on the fact that layers are sorted by
1585 // layerStack first (so we don't have to traverse the list
1586 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001587 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001588 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001589 if (i==0 || currentlayerStack != layerStack) {
1590 currentlayerStack = layerStack;
1591 // figure out if this layerstack is mirrored
1592 // (more than one display) if so, pick the default display,
1593 // if not, pick the only display it's on.
1594 disp.clear();
1595 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1596 sp<const DisplayDevice> hw(mDisplays[dpy]);
1597 if (hw->getLayerStack() == currentlayerStack) {
1598 if (disp == NULL) {
1599 disp = hw;
1600 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001601 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001602 break;
1603 }
1604 }
1605 }
1606 }
Chet Haase91d25932013-04-11 15:24:55 -07001607 if (disp == NULL) {
1608 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1609 // redraw after transform hint changes. See bug 8508397.
1610
1611 // could be null when this layer is using a layerStack
1612 // that is not visible on any display. Also can occur at
1613 // screen off/on times.
1614 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001615 }
Chet Haase91d25932013-04-11 15:24:55 -07001616 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001617 }
1618 }
1619
1620
Mathias Agopian3559b072012-08-15 13:46:03 -07001621 /*
1622 * Perform our own transaction if needed
1623 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001624
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001625 const LayerVector& layers(mDrawingState.layersSortedByZ);
1626 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001627 // layers have been added
1628 mVisibleRegionsDirty = true;
1629 }
1630
1631 // some layers might have been removed, so
1632 // we need to update the regions they're exposing.
1633 if (mLayersRemoved) {
1634 mLayersRemoved = false;
1635 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001636 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001637 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001638 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001639 if (currentLayers.indexOf(layer) < 0) {
1640 // this layer is not visible anymore
1641 // TODO: we could traverse the tree from front to back and
1642 // compute the actual visible region
1643 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001644 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001645 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001646 Region(Rect(s.active.w, s.active.h)));
1647 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001650 }
1651
1652 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001653
1654 updateCursorAsync();
1655}
1656
1657void SurfaceFlinger::updateCursorAsync()
1658{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001659 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1660 auto& displayDevice = mDisplays[displayId];
1661 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001662 continue;
1663 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001664
1665 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1666 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001667 }
1668 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001669}
1670
1671void SurfaceFlinger::commitTransaction()
1672{
1673 if (!mLayersPendingRemoval.isEmpty()) {
1674 // Notify removed layers now that they can't be drawn from
1675 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001676 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1677 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001678 mLayersPendingRemoval[i]->onRemoved();
1679 }
1680 mLayersPendingRemoval.clear();
1681 }
1682
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001683 // If this transaction is part of a window animation then the next frame
1684 // we composite should be considered an animation as well.
1685 mAnimCompositionPending = mAnimTransactionPending;
1686
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001688 mTransactionPending = false;
1689 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001690 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001691}
1692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001693void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001694 const LayerVector& currentLayers, uint32_t layerStack,
1695 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001696{
Mathias Agopian841cde52012-03-01 15:44:37 -08001697 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001698 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001700 Region aboveOpaqueLayers;
1701 Region aboveCoveredLayers;
1702 Region dirty;
1703
Mathias Agopian87baae12012-07-31 12:38:26 -07001704 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001705
1706 size_t i = currentLayers.size();
1707 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001708 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709
1710 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001711 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001712
Jesse Hall01e29052013-02-19 16:13:35 -08001713 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001714 if (s.layerStack != layerStack)
1715 continue;
1716
Mathias Agopianab028732010-03-16 16:41:46 -07001717 /*
1718 * opaqueRegion: area of a surface that is fully opaque.
1719 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001720 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001721
1722 /*
1723 * visibleRegion: area of a surface that is visible on screen
1724 * and not fully transparent. This is essentially the layer's
1725 * footprint minus the opaque regions above it.
1726 * Areas covered by a translucent surface are considered visible.
1727 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001728 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001729
1730 /*
1731 * coveredRegion: area of a surface that is covered by all
1732 * visible regions above it (which includes the translucent areas).
1733 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001734 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001735
Jesse Halla8026d22012-09-25 13:25:04 -07001736 /*
1737 * transparentRegion: area of a surface that is hinted to be completely
1738 * transparent. This is only used to tell when the layer has no visible
1739 * non-transparent regions and can be removed from the layer list. It
1740 * does not affect the visibleRegion of this layer or any layers
1741 * beneath it. The hint may not be correct if apps don't respect the
1742 * SurfaceView restrictions (which, sadly, some don't).
1743 */
1744 Region transparentRegion;
1745
Mathias Agopianab028732010-03-16 16:41:46 -07001746
1747 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001748 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001749 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001750 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001751 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001752 if (!visibleRegion.isEmpty()) {
1753 // Remove the transparent area from the visible region
1754 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001755 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001756 if (tr.preserveRects()) {
1757 // transform the transparent region
1758 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001759 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001760 // transformation too complex, can't do the
1761 // transparent region optimization.
1762 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001763 }
Mathias Agopianab028732010-03-16 16:41:46 -07001764 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001765
Mathias Agopianab028732010-03-16 16:41:46 -07001766 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001767 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001768 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001769 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1770 // the opaque region is the layer's footprint
1771 opaqueRegion = visibleRegion;
1772 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001773 }
1774 }
1775
Mathias Agopianab028732010-03-16 16:41:46 -07001776 // Clip the covered region to the visible region
1777 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1778
1779 // Update aboveCoveredLayers for next (lower) layer
1780 aboveCoveredLayers.orSelf(visibleRegion);
1781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001782 // subtract the opaque region covered by the layers above us
1783 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001784
1785 // compute this layer's dirty region
1786 if (layer->contentDirty) {
1787 // we need to invalidate the whole region
1788 dirty = visibleRegion;
1789 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001790 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001791 layer->contentDirty = false;
1792 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001793 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001794 * the exposed region consists of two components:
1795 * 1) what's VISIBLE now and was COVERED before
1796 * 2) what's EXPOSED now less what was EXPOSED before
1797 *
1798 * note that (1) is conservative, we start with the whole
1799 * visible region but only keep what used to be covered by
1800 * something -- which mean it may have been exposed.
1801 *
1802 * (2) handles areas that were not covered by anything but got
1803 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001804 */
Mathias Agopianab028732010-03-16 16:41:46 -07001805 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001806 const Region oldVisibleRegion = layer->visibleRegion;
1807 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001808 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1809 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001810 }
1811 dirty.subtractSelf(aboveOpaqueLayers);
1812
1813 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001814 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815
Mathias Agopianab028732010-03-16 16:41:46 -07001816 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001817 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001818
Jesse Halla8026d22012-09-25 13:25:04 -07001819 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820 layer->setVisibleRegion(visibleRegion);
1821 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001822 layer->setVisibleNonTransparentRegion(
1823 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824 }
1825
Mathias Agopian87baae12012-07-31 12:38:26 -07001826 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001827}
1828
Mathias Agopian87baae12012-07-31 12:38:26 -07001829void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1830 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001831 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001832 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1833 if (hw->getLayerStack() == layerStack) {
1834 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001835 }
1836 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001837}
1838
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001840{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 ALOGV("handlePageFlip");
1842
Mathias Agopian4fec8732012-06-29 14:12:52 -07001843 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001844
Mathias Agopian4fec8732012-06-29 14:12:52 -07001845 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001846 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001847 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001848
1849 // Store the set of layers that need updates. This set must not change as
1850 // buffers are being latched, as this could result in a deadlock.
1851 // Example: Two producers share the same command stream and:
1852 // 1.) Layer 0 is latched
1853 // 2.) Layer 0 gets a new frame
1854 // 2.) Layer 1 gets a new frame
1855 // 3.) Layer 1 is latched.
1856 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1857 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001858 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001859 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001860 if (layer->hasQueuedFrame()) {
1861 frameQueued = true;
1862 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001864 } else {
1865 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001866 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001867 } else {
1868 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001869 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001870 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001872 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001873 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001874 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001875 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001876 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001877
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001878 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001879
1880 // If we will need to wake up at some time in the future to deal with a
1881 // queued frame that shouldn't be displayed during this vsync period, wake
1882 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001883 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001884 signalLayerUpdate();
1885 }
1886
1887 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001889}
1890
Mathias Agopianad456f92011-01-13 17:53:01 -08001891void SurfaceFlinger::invalidateHwcGeometry()
1892{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001894}
1895
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001896
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001898 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899{
Dan Stoza71433162014-02-04 16:22:36 -08001900 // We only need to actually compose the display if:
1901 // 1) It is being handled by hardware composer, which may need this to
1902 // keep its virtual display state machine in sync, or
1903 // 2) There is work to be done (the dirty region isn't empty)
1904 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1905 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001907 return;
1908 }
1909
Dan Stoza9e56aa02015-11-02 13:00:03 -08001910 ALOGV("doDisplayComposition");
1911
Mathias Agopian87baae12012-07-31 12:38:26 -07001912 Region dirtyRegion(inDirtyRegion);
1913
Mathias Agopianb8a55602009-06-26 19:06:36 -07001914 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001915 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001916
Mathias Agopian42977342012-08-05 00:40:46 -07001917 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001918 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001919 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1920 // takes a rectangle, we must make sure to update that whole
1921 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001922 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001923 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001924 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001925 // We need to redraw the rectangle that will be updated
1926 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001927 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001928 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001929 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001930 } else {
1931 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001932 dirtyRegion.set(hw->bounds());
1933 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001934 }
1935 }
1936
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001937 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001939 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001940 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001941
1942 // swap buffers (presentation)
1943 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001944}
1945
Dan Stoza9e56aa02015-11-02 13:00:03 -08001946bool SurfaceFlinger::doComposeSurfaces(
1947 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001948{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001950
Dan Stoza9e56aa02015-11-02 13:00:03 -08001951 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001952
1953 mat4 oldColorMatrix;
1954 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
1955 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
1956 if (applyColorMatrix) {
1957 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1958 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
1959 }
1960
Dan Stoza9e56aa02015-11-02 13:00:03 -08001961 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1962 if (hasClientComposition) {
1963 ALOGV("hasClientComposition");
1964
1965 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001966 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001968 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1969 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1970 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1971 }
1972 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001973 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001974
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001975 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001976 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1977 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001978 // when using overlays, we assume a fully transparent framebuffer
1979 // NOTE: we could reduce how much we need to clear, for instance
1980 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001981 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001982 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001983 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001984 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001985 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001986 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001987
1988 // we remove the scissor part
1989 // we're left with the letterbox region
1990 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001991 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001992
1993 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001995
1996 // but limit it to the dirty region
1997 region.andSelf(dirty);
1998
Mathias Agopianb9494d52012-04-18 02:28:45 -07001999 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002000 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002001 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002002 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002003 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002004 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002005
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002007 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002008 // scissor on the main display. It should never be needed
2009 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 const Rect& bounds(displayDevice->getBounds());
2011 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002012 if (scissor != bounds) {
2013 // scissor doesn't match the screen's dimensions, so we
2014 // need to clear everything outside of it and enable
2015 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002016
Mathias Agopianf45c5102012-10-24 16:29:17 -07002017 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 const uint32_t height = displayDevice->getHeight();
2019 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002020 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002021 }
2022 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002023 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002024
Mathias Agopian85d751c2012-08-29 16:59:24 -07002025 /*
2026 * and then, render the layers targeted at the framebuffer
2027 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002028
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029 ALOGV("Rendering client layers");
2030 const Transform& displayTransform = displayDevice->getTransform();
2031 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002032 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 bool firstLayer = true;
2034 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2035 const Region clip(dirty.intersect(
2036 displayTransform.transform(layer->visibleRegion)));
2037 ALOGV("Layer: %s", layer->getName().string());
2038 ALOGV(" Composition type: %s",
2039 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002040 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 switch (layer->getCompositionType(hwcId)) {
2042 case HWC2::Composition::Cursor:
2043 case HWC2::Composition::Device:
2044 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002045 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2047 layer->isOpaque(state) && (state.alpha == 1.0f)
2048 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002049 // never clear the very first layer since we're
2050 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002051 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002052 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002053 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002054 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002055 case HWC2::Composition::Client: {
2056 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002057 break;
2058 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002060 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002061 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 } else {
2063 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002064 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002066 }
2067 } else {
2068 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002070 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002072 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002073 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002074 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002075 }
2076 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002077
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002078 if (applyColorMatrix) {
2079 getRenderEngine().setupColorTransform(oldColorMatrix);
2080 }
2081
Mathias Agopianf45c5102012-10-24 16:29:17 -07002082 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002083 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002084 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002085}
2086
Mathias Agopian3f844832013-08-07 21:24:32 -07002087void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002088 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002089 RenderEngine& engine(getRenderEngine());
2090 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002091}
2092
Dan Stoza7d89d062015-04-30 13:29:25 -07002093status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002094 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002095 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002096 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002097{
Dan Stoza7d89d062015-04-30 13:29:25 -07002098 // add this layer to the current state list
2099 {
2100 Mutex::Autolock _l(mStateLock);
2101 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2102 return NO_MEMORY;
2103 }
2104 mCurrentState.layersSortedByZ.add(lbc);
2105 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2106 }
2107
Mathias Agopian96f08192010-06-02 23:28:45 -07002108 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002109 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002110
Dan Stoza7d89d062015-04-30 13:29:25 -07002111 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002112}
2113
Mathias Agopian3f844832013-08-07 21:24:32 -07002114status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002115 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002116 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002117 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002118 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002119 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002120 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002121 return NO_ERROR;
2122 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002123 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002124}
2125
Dan Stozac7014012014-02-14 15:03:43 -08002126uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002127 return android_atomic_release_load(&mTransactionFlags);
2128}
2129
Mathias Agopian3f844832013-08-07 21:24:32 -07002130uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002131 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2132}
2133
Mathias Agopian3f844832013-08-07 21:24:32 -07002134uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002135 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2136 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002137 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138 }
2139 return old;
2140}
2141
Mathias Agopian8b33f032012-07-24 20:43:54 -07002142void SurfaceFlinger::setTransactionState(
2143 const Vector<ComposerState>& state,
2144 const Vector<DisplayState>& displays,
2145 uint32_t flags)
2146{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002147 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002148 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002149 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002150
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002151 if (flags & eAnimation) {
2152 // For window updates that are part of an animation we must wait for
2153 // previous animation "frames" to be handled.
2154 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002155 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002156 if (CC_UNLIKELY(err != NO_ERROR)) {
2157 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002158 // caller after a few seconds.
2159 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2160 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002161 mAnimTransactionPending = false;
2162 break;
2163 }
2164 }
2165 }
2166
Mathias Agopiane57f2922012-08-09 16:29:12 -07002167 size_t count = displays.size();
2168 for (size_t i=0 ; i<count ; i++) {
2169 const DisplayState& s(displays[i]);
2170 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002171 }
2172
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002174 for (size_t i=0 ; i<count ; i++) {
2175 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002176 // Here we need to check that the interface we're given is indeed
2177 // one of our own. A malicious client could give us a NULL
2178 // IInterface, or one of its own or even one of our own but a
2179 // different type. All these situations would cause us to crash.
2180 //
2181 // NOTE: it would be better to use RTTI as we could directly check
2182 // that we have a Client*. however, RTTI is disabled in Android.
2183 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002184 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002185 if (binder != NULL) {
2186 String16 desc(binder->getInterfaceDescriptor());
2187 if (desc == ISurfaceComposerClient::descriptor) {
2188 sp<Client> client( static_cast<Client *>(s.client.get()) );
2189 transactionFlags |= setClientStateLocked(client, s.state);
2190 }
2191 }
2192 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002193 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002194
Robert Carr2a7dbb42016-05-24 11:41:28 -07002195 // If a synchronous transaction is explicitly requested without any changes,
2196 // force a transaction anyway. This can be used as a flush mechanism for
2197 // previous async transactions.
2198 if (transactionFlags == 0 && (flags & eSynchronous)) {
2199 transactionFlags = eTransactionNeeded;
2200 }
2201
Mathias Agopian386aa982011-11-07 21:58:03 -08002202 if (transactionFlags) {
2203 // this triggers the transaction
2204 setTransactionFlags(transactionFlags);
2205
2206 // if this is a synchronous transaction, wait for it to take effect
2207 // before returning.
2208 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002209 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002210 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002211 if (flags & eAnimation) {
2212 mAnimTransactionPending = true;
2213 }
2214 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002215 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2216 if (CC_UNLIKELY(err != NO_ERROR)) {
2217 // just in case something goes wrong in SF, return to the
2218 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002219 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2220 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002221 break;
2222 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002224 }
2225}
2226
Mathias Agopiane57f2922012-08-09 16:29:12 -07002227uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2228{
Jesse Hall9a143922012-10-04 16:29:19 -07002229 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2230 if (dpyIdx < 0)
2231 return 0;
2232
Mathias Agopiane57f2922012-08-09 16:29:12 -07002233 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002234 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002235 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002236 const uint32_t what = s.what;
2237 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002238 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002239 disp.surface = s.surface;
2240 flags |= eDisplayTransactionNeeded;
2241 }
2242 }
2243 if (what & DisplayState::eLayerStackChanged) {
2244 if (disp.layerStack != s.layerStack) {
2245 disp.layerStack = s.layerStack;
2246 flags |= eDisplayTransactionNeeded;
2247 }
2248 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002249 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002250 if (disp.orientation != s.orientation) {
2251 disp.orientation = s.orientation;
2252 flags |= eDisplayTransactionNeeded;
2253 }
2254 if (disp.frame != s.frame) {
2255 disp.frame = s.frame;
2256 flags |= eDisplayTransactionNeeded;
2257 }
2258 if (disp.viewport != s.viewport) {
2259 disp.viewport = s.viewport;
2260 flags |= eDisplayTransactionNeeded;
2261 }
2262 }
Michael Lentine47e45402014-07-18 15:34:25 -07002263 if (what & DisplayState::eDisplaySizeChanged) {
2264 if (disp.width != s.width) {
2265 disp.width = s.width;
2266 flags |= eDisplayTransactionNeeded;
2267 }
2268 if (disp.height != s.height) {
2269 disp.height = s.height;
2270 flags |= eDisplayTransactionNeeded;
2271 }
2272 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002273 }
2274 return flags;
2275}
2276
2277uint32_t SurfaceFlinger::setClientStateLocked(
2278 const sp<Client>& client,
2279 const layer_state_t& s)
2280{
2281 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002282 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002283 if (layer != 0) {
2284 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002285 bool geometryAppliesWithResize =
2286 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002287 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002288 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002289 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002290 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002291 }
2292 if (what & layer_state_t::eLayerChanged) {
2293 // NOTE: index needs to be calculated before we update the state
2294 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002295 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002296 mCurrentState.layersSortedByZ.removeAt(idx);
2297 mCurrentState.layersSortedByZ.add(layer);
2298 // we need traversal (state changed)
2299 // AND transaction (list changed)
2300 flags |= eTransactionNeeded|eTraversalNeeded;
2301 }
2302 }
2303 if (what & layer_state_t::eSizeChanged) {
2304 if (layer->setSize(s.w, s.h)) {
2305 flags |= eTraversalNeeded;
2306 }
2307 }
2308 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002309 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002310 flags |= eTraversalNeeded;
2311 }
2312 if (what & layer_state_t::eMatrixChanged) {
2313 if (layer->setMatrix(s.matrix))
2314 flags |= eTraversalNeeded;
2315 }
2316 if (what & layer_state_t::eTransparentRegionChanged) {
2317 if (layer->setTransparentRegionHint(s.transparentRegion))
2318 flags |= eTraversalNeeded;
2319 }
Dan Stoza23116082015-06-18 14:58:39 -07002320 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002321 if (layer->setFlags(s.flags, s.mask))
2322 flags |= eTraversalNeeded;
2323 }
2324 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002325 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002326 flags |= eTraversalNeeded;
2327 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002328 if (what & layer_state_t::eFinalCropChanged) {
2329 if (layer->setFinalCrop(s.finalCrop))
2330 flags |= eTraversalNeeded;
2331 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002332 if (what & layer_state_t::eLayerStackChanged) {
2333 // NOTE: index needs to be calculated before we update the state
2334 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002335 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002336 mCurrentState.layersSortedByZ.removeAt(idx);
2337 mCurrentState.layersSortedByZ.add(layer);
2338 // we need traversal (state changed)
2339 // AND transaction (list changed)
2340 flags |= eTransactionNeeded|eTraversalNeeded;
2341 }
2342 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002343 if (what & layer_state_t::eDeferTransaction) {
2344 layer->deferTransactionUntil(s.handle, s.frameNumber);
2345 // We don't trigger a traversal here because if no other state is
2346 // changed, we don't want this to cause any more work
2347 }
Robert Carrc3574f72016-03-24 12:19:32 -07002348 if (what & layer_state_t::eOverrideScalingModeChanged) {
2349 layer->setOverrideScalingMode(s.overrideScalingMode);
2350 // We don't trigger a traversal here because if no other state is
2351 // changed, we don't want this to cause any more work
2352 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002353 }
2354 return flags;
2355}
2356
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002357status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002358 const String8& name,
2359 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002360 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2361 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002362{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002363 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002364 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002365 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002366 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002367 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002368 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002369
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002370 status_t result = NO_ERROR;
2371
2372 sp<Layer> layer;
2373
Mathias Agopian3165cc22012-08-08 19:42:09 -07002374 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2375 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002376 result = createNormalLayer(client,
2377 name, w, h, flags, format,
2378 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002379 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002380 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002381 result = createDimLayer(client,
2382 name, w, h, flags,
2383 handle, gbp, &layer);
2384 break;
2385 default:
2386 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 break;
2388 }
2389
Dan Stoza7d89d062015-04-30 13:29:25 -07002390 if (result != NO_ERROR) {
2391 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002393
2394 result = addClientLayer(client, *handle, *gbp, layer);
2395 if (result != NO_ERROR) {
2396 return result;
2397 }
2398
2399 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002400 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401}
2402
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002403status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2404 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2405 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406{
2407 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002408 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409 case PIXEL_FORMAT_TRANSPARENT:
2410 case PIXEL_FORMAT_TRANSLUCENT:
2411 format = PIXEL_FORMAT_RGBA_8888;
2412 break;
2413 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002414 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002415 break;
2416 }
2417
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002418 *outLayer = new Layer(this, client, name, w, h, flags);
2419 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2420 if (err == NO_ERROR) {
2421 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002422 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002423 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002424
2425 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2426 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427}
2428
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002429status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2430 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2431 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002433 *outLayer = new LayerDim(this, client, name, w, h, flags);
2434 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002435 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002436 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002437}
2438
Mathias Agopianac9fa422013-02-11 16:40:36 -08002439status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440{
Mathias Agopian67106042013-03-14 19:18:13 -07002441 // called by the window manager when it wants to remove a Layer
2442 status_t err = NO_ERROR;
2443 sp<Layer> l(client->getLayerUser(handle));
2444 if (l != NULL) {
2445 err = removeLayer(l);
2446 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2447 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002448 }
2449 return err;
2450}
2451
Mathias Agopian13127d82013-03-05 17:47:11 -08002452status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002453{
Mathias Agopian67106042013-03-14 19:18:13 -07002454 // called by ~LayerCleaner() when all references to the IBinder (handle)
2455 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002456 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002457 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002458 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002459 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002460 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002461 "error removing layer=%p (%s)", l.get(), strerror(-err));
2462 }
2463 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464}
2465
Mathias Agopianb60314a2012-04-10 22:09:54 -07002466// ---------------------------------------------------------------------------
2467
Andy McFadden13a082e2012-08-24 10:16:42 -07002468void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002469 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002470 Vector<ComposerState> state;
2471 Vector<DisplayState> displays;
2472 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002473 d.what = DisplayState::eDisplayProjectionChanged |
2474 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002475 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002476 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002477 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002478 d.frame.makeInvalid();
2479 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002480 d.width = 0;
2481 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002482 displays.add(d);
2483 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002484 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002485
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2487 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002488 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002489}
2490
2491void SurfaceFlinger::initializeDisplays() {
2492 class MessageScreenInitialized : public MessageBase {
2493 SurfaceFlinger* flinger;
2494 public:
2495 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2496 virtual bool handler() {
2497 flinger->onInitializeDisplays();
2498 return true;
2499 }
2500 };
2501 sp<MessageBase> msg = new MessageScreenInitialized(this);
2502 postMessageAsync(msg); // we may be called from main thread, use async message
2503}
2504
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002505void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2506 int mode) {
2507 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2508 this);
2509 int32_t type = hw->getDisplayType();
2510 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002511
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002512 if (mode == currentMode) {
2513 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002514 return;
2515 }
2516
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002517 hw->setPowerMode(mode);
2518 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2519 ALOGW("Trying to set power mode for virtual display");
2520 return;
2521 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002522
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002523 if (currentMode == HWC_POWER_MODE_OFF) {
2524 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002525 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2526 // FIXME: eventthread only knows about the main display right now
2527 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002528 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002530
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002531 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002532 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002533 repaintEverything();
2534 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002535 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002536 disableHardwareVsync(true); // also cancels any in-progress resync
2537
Mathias Agopiancde87a32012-09-13 14:09:01 -07002538 // FIXME: eventthread only knows about the main display right now
2539 mEventThread->onScreenReleased();
2540 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002541
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002542 getHwComposer().setPowerMode(type, mode);
2543 mVisibleRegionsDirty = true;
2544 // from this point on, SF will stop drawing on this display
2545 } else {
2546 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002547 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002548}
2549
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002550void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2551 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002552 SurfaceFlinger& mFlinger;
2553 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002554 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002555 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002556 MessageSetPowerMode(SurfaceFlinger& flinger,
2557 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2558 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002559 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002560 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002561 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002562 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002563 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002564 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002565 ALOGW("Attempt to set power mode = %d for virtual display",
2566 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002567 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002568 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002569 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002570 return true;
2571 }
2572 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002573 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002574 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002575}
2576
2577// ---------------------------------------------------------------------------
2578
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2580{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002582
Mathias Agopianbd115332013-04-18 16:41:04 -07002583 IPCThreadState* ipc = IPCThreadState::self();
2584 const int pid = ipc->getCallingPid();
2585 const int uid = ipc->getCallingUid();
2586 if ((uid != AID_SHELL) &&
2587 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002588 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002589 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002591 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002592 // (this would indicate SF is stuck, but we want to be able to
2593 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002594 status_t err = mStateLock.timedLock(s2ns(1));
2595 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002596 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002597 result.appendFormat(
2598 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2599 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002600 }
2601
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002602 bool dumpAll = true;
2603 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002604 size_t numArgs = args.size();
2605 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002606 if ((index < numArgs) &&
2607 (args[index] == String16("--list"))) {
2608 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002609 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002610 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002611 }
2612
2613 if ((index < numArgs) &&
2614 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002615 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002616 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002617 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002618 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002619
2620 if ((index < numArgs) &&
2621 (args[index] == String16("--latency-clear"))) {
2622 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002623 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002624 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002625 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002626
2627 if ((index < numArgs) &&
2628 (args[index] == String16("--dispsync"))) {
2629 index++;
2630 mPrimaryDispSync.dump(result);
2631 dumpAll = false;
2632 }
Dan Stozab90cf072015-03-05 11:05:59 -08002633
2634 if ((index < numArgs) &&
2635 (args[index] == String16("--static-screen"))) {
2636 index++;
2637 dumpStaticScreenStats(result);
2638 dumpAll = false;
2639 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002640
2641 if ((index < numArgs) &&
2642 (args[index] == String16("--fences"))) {
2643 index++;
2644 mFenceTracker.dump(&result);
2645 dumpAll = false;
2646 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002647 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002648
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002649 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002650 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002651 }
2652
Mathias Agopian9795c422009-08-26 16:36:26 -07002653 if (locked) {
2654 mStateLock.unlock();
2655 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 }
2657 write(fd, result.string(), result.size());
2658 return NO_ERROR;
2659}
2660
Dan Stozac7014012014-02-14 15:03:43 -08002661void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2662 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002663{
2664 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2665 const size_t count = currentLayers.size();
2666 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002667 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002668 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002669 }
2670}
2671
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002672void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002673 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002674{
2675 String8 name;
2676 if (index < args.size()) {
2677 name = String8(args[index]);
2678 index++;
2679 }
2680
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2682 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002683 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002684
2685 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002686 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002687 } else {
2688 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2689 const size_t count = currentLayers.size();
2690 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002691 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002692 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002693 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002694 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002695 }
2696 }
2697}
2698
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002699void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002700 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002701{
2702 String8 name;
2703 if (index < args.size()) {
2704 name = String8(args[index]);
2705 index++;
2706 }
2707
2708 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2709 const size_t count = currentLayers.size();
2710 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002711 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002712 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002713 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002714 }
2715 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002716
Svetoslavd85084b2014-03-20 10:28:31 -07002717 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002718}
2719
Jamie Gennis6547ff42013-07-16 20:12:42 -07002720// This should only be called from the main thread. Otherwise it would need
2721// the lock and should use mCurrentState rather than mDrawingState.
2722void SurfaceFlinger::logFrameStats() {
2723 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2724 const size_t count = drawingLayers.size();
2725 for (size_t i=0 ; i<count ; i++) {
2726 const sp<Layer>& layer(drawingLayers[i]);
2727 layer->logFrameStats();
2728 }
2729
2730 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2731}
2732
Andy McFadden4803b742012-09-24 19:07:20 -07002733/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2734{
2735 static const char* config =
2736 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002737#ifdef HAS_CONTEXT_PRIORITY
2738 " HAS_CONTEXT_PRIORITY"
2739#endif
2740#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2741 " NEVER_DEFAULT_TO_ASYNC_MODE"
2742#endif
2743#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2744 " TARGET_DISABLE_TRIPLE_BUFFERING"
2745#endif
2746 "]";
2747 result.append(config);
2748}
2749
Dan Stozab90cf072015-03-05 11:05:59 -08002750void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2751{
2752 result.appendFormat("Static screen stats:\n");
2753 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2754 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2755 float percent = 100.0f *
2756 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2757 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2758 b + 1, bucketTimeSec, percent);
2759 }
2760 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2761 float percent = 100.0f *
2762 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2763 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2764 NUM_BUCKETS - 1, bucketTimeSec, percent);
2765}
2766
Dan Stozae77c7662016-05-13 11:37:28 -07002767void SurfaceFlinger::recordBufferingStats(const char* layerName,
2768 std::vector<OccupancyTracker::Segment>&& history) {
2769 Mutex::Autolock lock(mBufferingStatsMutex);
2770 auto& stats = mBufferingStats[layerName];
2771 for (const auto& segment : history) {
2772 if (!segment.usedThirdBuffer) {
2773 stats.twoBufferTime += segment.totalTime;
2774 }
2775 if (segment.occupancyAverage < 1.0f) {
2776 stats.doubleBufferedTime += segment.totalTime;
2777 } else if (segment.occupancyAverage < 2.0f) {
2778 stats.tripleBufferedTime += segment.totalTime;
2779 }
2780 ++stats.numSegments;
2781 stats.totalTime += segment.totalTime;
2782 }
2783}
2784
2785void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2786 result.append("Buffering stats:\n");
2787 result.append(" [Layer name] <Active time> <Two buffer> "
2788 "<Double buffered> <Triple buffered>\n");
2789 Mutex::Autolock lock(mBufferingStatsMutex);
2790 typedef std::tuple<std::string, float, float, float> BufferTuple;
2791 std::map<float, BufferTuple, std::greater<float>> sorted;
2792 for (const auto& statsPair : mBufferingStats) {
2793 const char* name = statsPair.first.c_str();
2794 const BufferingStats& stats = statsPair.second;
2795 if (stats.numSegments == 0) {
2796 continue;
2797 }
2798 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2799 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2800 stats.totalTime;
2801 float doubleBufferRatio = static_cast<float>(
2802 stats.doubleBufferedTime) / stats.totalTime;
2803 float tripleBufferRatio = static_cast<float>(
2804 stats.tripleBufferedTime) / stats.totalTime;
2805 sorted.insert({activeTime, {name, twoBufferRatio,
2806 doubleBufferRatio, tripleBufferRatio}});
2807 }
2808 for (const auto& sortedPair : sorted) {
2809 float activeTime = sortedPair.first;
2810 const BufferTuple& values = sortedPair.second;
2811 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2812 std::get<0>(values).c_str(), activeTime,
2813 std::get<1>(values), std::get<2>(values),
2814 std::get<3>(values));
2815 }
2816 result.append("\n");
2817}
2818
2819
Mathias Agopian74d211a2013-04-22 16:55:35 +02002820void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2821 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002822{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002823 bool colorize = false;
2824 if (index < args.size()
2825 && (args[index] == String16("--color"))) {
2826 colorize = true;
2827 index++;
2828 }
2829
2830 Colorizer colorizer(colorize);
2831
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002832 // figure out if we're stuck somewhere
2833 const nsecs_t now = systemTime();
2834 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2835 const nsecs_t inTransaction(mDebugInTransaction);
2836 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2837 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2838
2839 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002840 * Dump library configuration.
2841 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002842
2843 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002844 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002845 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002846 appendSfConfigString(result);
2847 appendUiConfigString(result);
2848 appendGuiConfigString(result);
2849 result.append("\n");
2850
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002851 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002852 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002853 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002854 result.append(SyncFeatures::getInstance().toString());
2855 result.append("\n");
2856
Dan Stoza9e56aa02015-11-02 13:00:03 -08002857 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2858
Andy McFadden41d67d72014-04-25 16:58:34 -07002859 colorizer.bold(result);
2860 result.append("DispSync configuration: ");
2861 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002862 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2863 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002864 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2865 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002866 result.append("\n");
2867
Dan Stozab90cf072015-03-05 11:05:59 -08002868 // Dump static screen stats
2869 result.append("\n");
2870 dumpStaticScreenStats(result);
2871 result.append("\n");
2872
Dan Stozae77c7662016-05-13 11:37:28 -07002873 dumpBufferingStats(result);
2874
Andy McFadden4803b742012-09-24 19:07:20 -07002875 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002876 * Dump the visible layer list
2877 */
2878 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2879 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002880 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002881 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002882 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002883 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002884 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002885 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002886 }
2887
2888 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002889 * Dump Display state
2890 */
2891
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002892 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002893 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002894 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002895 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2896 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002897 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002898 }
2899
2900 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002901 * Dump SurfaceFlinger global state
2902 */
2903
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002904 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002905 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002906 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002907
Mathias Agopian888c8222012-08-04 21:10:38 -07002908 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002909 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002910
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002911 colorizer.bold(result);
2912 result.appendFormat("EGL implementation : %s\n",
2913 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2914 colorizer.reset(result);
2915 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002916 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002917
Mathias Agopian875d8e12013-06-07 15:35:48 -07002918 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002919
Mathias Agopian42977342012-08-05 00:40:46 -07002920 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002921 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2922 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002923 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002924 " last eglSwapBuffers() time: %f us\n"
2925 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002926 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002927 " refresh-rate : %f fps\n"
2928 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002929 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002930 " gpu_to_cpu_unsupported : %d\n"
2931 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002932 mLastSwapBufferTime/1000.0,
2933 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002934 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 1e9 / activeConfig->getVsyncPeriod(),
2936 activeConfig->getDpiX(),
2937 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002938 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002939
Mathias Agopian74d211a2013-04-22 16:55:35 +02002940 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002941 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002942
Mathias Agopian74d211a2013-04-22 16:55:35 +02002943 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002944 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002945
2946 /*
2947 * VSYNC state
2948 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002949 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002950
2951 /*
2952 * Dump HWComposer state
2953 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002954 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002955 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002956 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002957 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002958 result.appendFormat(" h/w composer %s\n",
2959 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002960 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002961
2962 /*
2963 * Dump gralloc state
2964 */
2965 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2966 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002967}
2968
Mathias Agopian13127d82013-03-05 17:47:11 -08002969const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002970SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002971 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002972 wp<IBinder> dpy;
2973 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2974 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2975 dpy = mDisplays.keyAt(i);
2976 break;
2977 }
2978 }
2979 if (dpy == NULL) {
2980 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2981 // Just use the primary display so we have something to return
2982 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2983 }
2984 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002985}
2986
Keun young Park63f165f2012-08-31 10:53:36 -07002987bool SurfaceFlinger::startDdmConnection()
2988{
2989 void* libddmconnection_dso =
2990 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2991 if (!libddmconnection_dso) {
2992 return false;
2993 }
2994 void (*DdmConnection_start)(const char* name);
2995 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002996 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002997 if (!DdmConnection_start) {
2998 dlclose(libddmconnection_dso);
2999 return false;
3000 }
3001 (*DdmConnection_start)(getServiceName());
3002 return true;
3003}
3004
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005status_t SurfaceFlinger::onTransact(
3006 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3007{
3008 switch (code) {
3009 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003010 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003011 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003012 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003013 case CLEAR_ANIMATION_FRAME_STATS:
3014 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003015 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003016 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017 {
3018 // codes that require permission check
3019 IPCThreadState* ipc = IPCThreadState::self();
3020 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003021 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003022 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003023 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003024 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003025 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3026 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003028 break;
3029 }
3030 case CAPTURE_SCREEN:
3031 {
3032 // codes that require permission check
3033 IPCThreadState* ipc = IPCThreadState::self();
3034 const int pid = ipc->getCallingPid();
3035 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003036 if ((uid != AID_GRAPHICS) &&
3037 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003038 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003039 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3040 return PERMISSION_DENIED;
3041 }
3042 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043 }
3044 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003045
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003046 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3047 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003048 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003049 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003050 IPCThreadState* ipc = IPCThreadState::self();
3051 const int pid = ipc->getCallingPid();
3052 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003053 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003054 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003055 return PERMISSION_DENIED;
3056 }
3057 int n;
3058 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003059 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003060 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003061 return NO_ERROR;
3062 case 1002: // SHOW_UPDATES
3063 n = data.readInt32();
3064 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003065 invalidateHwcGeometry();
3066 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003069 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003070 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003072 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 setTransactionFlags(
3074 eTransactionNeeded|
3075 eDisplayTransactionNeeded|
3076 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003077 return NO_ERROR;
3078 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003079 case 1006:{ // send empty update
3080 signalRefresh();
3081 return NO_ERROR;
3082 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003083 case 1008: // toggle use of hw composer
3084 n = data.readInt32();
3085 mDebugDisableHWC = n ? 1 : 0;
3086 invalidateHwcGeometry();
3087 repaintEverything();
3088 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003089 case 1009: // toggle use of transform hint
3090 n = data.readInt32();
3091 mDebugDisableTransformHint = n ? 1 : 0;
3092 invalidateHwcGeometry();
3093 repaintEverything();
3094 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003095 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003096 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097 reply->writeInt32(0);
3098 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003099 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003100 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 return NO_ERROR;
3102 case 1013: {
3103 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003104 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3105 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003106 return NO_ERROR;
3107 }
3108 case 1014: {
3109 // daltonize
3110 n = data.readInt32();
3111 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003112 case 1:
3113 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3114 break;
3115 case 2:
3116 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3117 break;
3118 case 3:
3119 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3120 break;
3121 default:
3122 mDaltonizer.setType(ColorBlindnessType::None);
3123 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003124 }
3125 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003126 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003127 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003128 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003129 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003130 invalidateHwcGeometry();
3131 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003132 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003134 case 1015: {
3135 // apply a color matrix
3136 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003137 if (n) {
3138 // color matrix is sent as mat3 matrix followed by vec3
3139 // offset, then packed into a mat4 where the last row is
3140 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003141 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003142 for (size_t j = 0; j < 4; j++) {
3143 mColorMatrix[i][j] = data.readFloat();
3144 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003145 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003146 } else {
3147 mColorMatrix = mat4();
3148 }
3149 invalidateHwcGeometry();
3150 repaintEverything();
3151 return NO_ERROR;
3152 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003153 // This is an experimental interface
3154 // Needs to be shifted to proper binder interface when we productize
3155 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003156 n = data.readInt32();
3157 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003158 return NO_ERROR;
3159 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003160 case 1017: {
3161 n = data.readInt32();
3162 mForceFullDamage = static_cast<bool>(n);
3163 return NO_ERROR;
3164 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003165 case 1018: { // Modify Choreographer's phase offset
3166 n = data.readInt32();
3167 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3168 return NO_ERROR;
3169 }
3170 case 1019: { // Modify SurfaceFlinger's phase offset
3171 n = data.readInt32();
3172 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3173 return NO_ERROR;
3174 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 }
3176 }
3177 return err;
3178}
3179
Mathias Agopian53331da2011-08-22 21:44:41 -07003180void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003181 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003182 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003183}
3184
Mathias Agopian59119e62010-10-11 12:37:43 -07003185// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003186// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003187// ---------------------------------------------------------------------------
3188
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003189/* The code below is here to handle b/8734824
3190 *
3191 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003192 * from the surfaceflinger thread to the calling binder thread, where they
3193 * are executed. This allows the calling thread in the calling process to be
3194 * reused and not depend on having "enough" binder threads to handle the
3195 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003196 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003197class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003198 /* Parts of GraphicProducerWrapper are run on two different threads,
3199 * communicating by sending messages via Looper but also by shared member
3200 * data. Coherence maintenance is subtle and in places implicit (ugh).
3201 *
3202 * Don't rely on Looper's sendMessage/handleMessage providing
3203 * release/acquire semantics for any data not actually in the Message.
3204 * Data going from surfaceflinger to binder threads needs to be
3205 * synchronized explicitly.
3206 *
3207 * Barrier open/wait do provide release/acquire semantics. This provides
3208 * implicit synchronization for data coming back from binder to
3209 * surfaceflinger threads.
3210 */
3211
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003212 sp<IGraphicBufferProducer> impl;
3213 sp<Looper> looper;
3214 status_t result;
3215 bool exitPending;
3216 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003217 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003218 uint32_t code;
3219 Parcel const* data;
3220 Parcel* reply;
3221
3222 enum {
3223 MSG_API_CALL,
3224 MSG_EXIT
3225 };
3226
3227 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003228 * Called on surfaceflinger thread. This is called by our "fake"
3229 * BpGraphicBufferProducer. We package the data and reply Parcel and
3230 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003231 */
3232 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003233 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003234 this->code = code;
3235 this->data = &data;
3236 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003237 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003238 // if we've exited, we run the message synchronously right here.
3239 // note (JH): as far as I can tell from looking at the code, this
3240 // never actually happens. if it does, i'm not sure if it happens
3241 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003242 handleMessage(Message(MSG_API_CALL));
3243 } else {
3244 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003245 // Prevent stores to this->{code, data, reply} from being
3246 // reordered later than the construction of Message.
3247 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003248 looper->sendMessage(this, Message(MSG_API_CALL));
3249 barrier.wait();
3250 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003251 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003252 }
3253
3254 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003255 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003256 * call the real BpGraphicBufferProducer.
3257 */
3258 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003259 int what = message.what;
3260 // Prevent reads below from happening before the read from Message
3261 atomic_thread_fence(memory_order_acquire);
3262 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003263 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003264 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003265 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003266 exitRequested = true;
3267 }
3268 }
3269
3270public:
Jesse Hallb154c422014-07-13 12:47:02 -07003271 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3272 : impl(impl),
3273 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003274 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003275 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003276 exitRequested(false),
3277 code(0),
3278 data(NULL),
3279 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003280 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003281
Jesse Hallb154c422014-07-13 12:47:02 -07003282 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003283 status_t waitForResponse() {
3284 do {
3285 looper->pollOnce(-1);
3286 } while (!exitRequested);
3287 return result;
3288 }
3289
Jesse Hallb154c422014-07-13 12:47:02 -07003290 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003291 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003292 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003293 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003294 // Ensure this->result is visible to the binder thread before it
3295 // handles the message.
3296 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003297 looper->sendMessage(this, Message(MSG_EXIT));
3298 }
3299};
3300
3301
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003302status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3303 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003304 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003305 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003306 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003307
3308 if (CC_UNLIKELY(display == 0))
3309 return BAD_VALUE;
3310
3311 if (CC_UNLIKELY(producer == 0))
3312 return BAD_VALUE;
3313
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003314 // if we have secure windows on this display, never allow the screen capture
3315 // unless the producer interface is local (i.e.: we can take a screenshot for
3316 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003317 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003318
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003319 // Convert to surfaceflinger's internal rotation type.
3320 Transform::orientation_flags rotationFlags;
3321 switch (rotation) {
3322 case ISurfaceComposer::eRotateNone:
3323 rotationFlags = Transform::ROT_0;
3324 break;
3325 case ISurfaceComposer::eRotate90:
3326 rotationFlags = Transform::ROT_90;
3327 break;
3328 case ISurfaceComposer::eRotate180:
3329 rotationFlags = Transform::ROT_180;
3330 break;
3331 case ISurfaceComposer::eRotate270:
3332 rotationFlags = Transform::ROT_270;
3333 break;
3334 default:
3335 rotationFlags = Transform::ROT_0;
3336 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3337 break;
3338 }
3339
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003340 class MessageCaptureScreen : public MessageBase {
3341 SurfaceFlinger* flinger;
3342 sp<IBinder> display;
3343 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003344 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003345 uint32_t reqWidth, reqHeight;
3346 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003347 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003348 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003349 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003350 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003351 public:
3352 MessageCaptureScreen(SurfaceFlinger* flinger,
3353 const sp<IBinder>& display,
3354 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003355 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003356 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003357 bool useIdentityTransform,
3358 Transform::orientation_flags rotation,
3359 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003360 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003361 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003362 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003363 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003364 rotation(rotation), result(PERMISSION_DENIED),
3365 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003366 {
3367 }
3368 status_t getResult() const {
3369 return result;
3370 }
3371 virtual bool handler() {
3372 Mutex::Autolock _l(flinger->mStateLock);
3373 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003374 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003375 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003376 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003377 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003378 return true;
3379 }
3380 };
3381
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003382 // this creates a "fake" BBinder which will serve as a "fake" remote
3383 // binder to receive the marshaled calls and forward them to the
3384 // real remote (a BpGraphicBufferProducer)
3385 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3386
3387 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3388 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003389 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003390 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003391 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003392 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003393
3394 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003395 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003396 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003397 }
3398 return res;
3399}
3400
Mathias Agopian180f10d2013-04-10 22:55:41 -07003401
3402void SurfaceFlinger::renderScreenImplLocked(
3403 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003404 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003405 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003406 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003407{
3408 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003409 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003410
3411 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003412 const int32_t hw_w = hw->getWidth();
3413 const int32_t hw_h = hw->getHeight();
3414 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003415 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003416
Dan Stozac1879002014-05-22 15:59:05 -07003417 // if a default or invalid sourceCrop is passed in, set reasonable values
3418 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3419 !sourceCrop.isValid()) {
3420 sourceCrop.setLeftTop(Point(0, 0));
3421 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3422 }
3423
3424 // ensure that sourceCrop is inside screen
3425 if (sourceCrop.left < 0) {
3426 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3427 }
Dan Stozabe31f442014-06-11 11:20:54 -07003428 if (sourceCrop.right > hw_w) {
3429 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003430 }
3431 if (sourceCrop.top < 0) {
3432 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3433 }
Dan Stozabe31f442014-06-11 11:20:54 -07003434 if (sourceCrop.bottom > hw_h) {
3435 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003436 }
3437
Mathias Agopian180f10d2013-04-10 22:55:41 -07003438 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003439 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003440
3441 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003442 engine.setViewportAndProjection(
3443 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003444 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003445
3446 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003447 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003448
3449 const LayerVector& layers( mDrawingState.layersSortedByZ );
3450 const size_t count = layers.size();
3451 for (size_t i=0 ; i<count ; ++i) {
3452 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003453 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003454 if (state.layerStack == hw->getLayerStack()) {
3455 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3456 if (layer->isVisible()) {
3457 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003458 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003459 if (filtering) layer->setFiltering(false);
3460 }
3461 }
3462 }
3463 }
3464
Mathias Agopian931bda12013-08-28 18:11:46 -07003465 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003466}
3467
3468
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003469status_t SurfaceFlinger::captureScreenImplLocked(
3470 const sp<const DisplayDevice>& hw,
3471 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003472 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003473 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003474 bool useIdentityTransform, Transform::orientation_flags rotation,
3475 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003476{
3477 ATRACE_CALL();
3478
Mathias Agopian180f10d2013-04-10 22:55:41 -07003479 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003480 uint32_t hw_w = hw->getWidth();
3481 uint32_t hw_h = hw->getHeight();
3482
3483 if (rotation & Transform::ROT_90) {
3484 std::swap(hw_w, hw_h);
3485 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003486
Mathias Agopian180f10d2013-04-10 22:55:41 -07003487 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3488 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3489 reqWidth, reqHeight, hw_w, hw_h);
3490 return BAD_VALUE;
3491 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003492
Mathias Agopian180f10d2013-04-10 22:55:41 -07003493 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3494 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3495
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003496 bool secureLayerIsVisible = false;
3497 const LayerVector& layers(mDrawingState.layersSortedByZ);
3498 const size_t count = layers.size();
3499 for (size_t i = 0 ; i < count ; ++i) {
3500 const sp<Layer>& layer(layers[i]);
3501 const Layer::State& state(layer->getDrawingState());
3502 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3503 state.z <= maxLayerZ && layer->isVisible() &&
3504 layer->isSecure()) {
3505 secureLayerIsVisible = true;
3506 }
3507 }
3508
3509 if (!isLocalScreenshot && secureLayerIsVisible) {
3510 ALOGW("FB is protected: PERMISSION_DENIED");
3511 return PERMISSION_DENIED;
3512 }
3513
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003514 // create a surface (because we're a producer, and we need to
3515 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003516 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003517 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003518
Michael Lentine5a16a622015-05-21 13:48:24 -07003519 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3520 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003521 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3522 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003523
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003524 int err = 0;
3525 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003526 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003527 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3528 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003529
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003530 if (err == NO_ERROR) {
3531 ANativeWindowBuffer* buffer;
3532 /* TODO: Once we have the sync framework everywhere this can use
3533 * server-side waits on the fence that dequeueBuffer returns.
3534 */
3535 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3536 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003537 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003538 // create an EGLImage from the buffer so we can later
3539 // turn it into a texture
3540 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3541 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3542 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003543 // this binds the given EGLImage as a framebuffer for the
3544 // duration of this scope.
3545 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3546 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003547 // this will in fact render into our dequeued buffer
3548 // via an FBO, which means we didn't have to create
3549 // an EGLSurface and therefore we're not
3550 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003551 renderScreenImplLocked(
3552 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3553 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003554
Riley Andrews86639902014-08-15 12:27:24 -07003555 // Attempt to create a sync khr object that can produce a sync point. If that
3556 // isn't available, create a non-dupable sync object in the fallback path and
3557 // wait on it directly.
3558 EGLSyncKHR sync;
3559 if (!DEBUG_SCREENSHOTS) {
3560 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003561 // native fence fd will not be populated until flush() is done.
3562 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003563 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003564 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003565 }
Riley Andrews86639902014-08-15 12:27:24 -07003566 if (sync != EGL_NO_SYNC_KHR) {
3567 // get the sync fd
3568 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3569 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3570 ALOGW("captureScreen: failed to dup sync khr object");
3571 syncFd = -1;
3572 }
3573 eglDestroySyncKHR(mEGLDisplay, sync);
3574 } else {
3575 // fallback path
3576 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3577 if (sync != EGL_NO_SYNC_KHR) {
3578 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3579 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3580 EGLint eglErr = eglGetError();
3581 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3582 ALOGW("captureScreen: fence wait timed out");
3583 } else {
3584 ALOGW_IF(eglErr != EGL_SUCCESS,
3585 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3586 }
3587 eglDestroySyncKHR(mEGLDisplay, sync);
3588 } else {
3589 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3590 }
3591 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003592 if (DEBUG_SCREENSHOTS) {
3593 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3594 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3595 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3596 hw, minLayerZ, maxLayerZ);
3597 delete [] pixels;
3598 }
3599
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003600 } else {
3601 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3602 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003603 window->cancelBuffer(window, buffer, syncFd);
3604 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003605 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003606 // destroy our image
3607 eglDestroyImageKHR(mEGLDisplay, image);
3608 } else {
3609 result = BAD_VALUE;
3610 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003611 if (buffer) {
3612 // queueBuffer takes ownership of syncFd
3613 result = window->queueBuffer(window, buffer, syncFd);
3614 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003615 }
3616 } else {
3617 result = BAD_VALUE;
3618 }
3619 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3620 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003621
Mathias Agopian74c40c02010-09-29 13:02:36 -07003622 return result;
3623}
3624
Mathias Agopiand5556842013-09-19 17:08:37 -07003625void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3626 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003627 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003628 for (size_t y=0 ; y<h ; y++) {
3629 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3630 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003631 if (p[x] != 0xFF000000) return;
3632 }
3633 }
3634 ALOGE("*** we just took a black screenshot ***\n"
3635 "requested minz=%d, maxz=%d, layerStack=%d",
3636 minLayerZ, maxLayerZ, hw->getLayerStack());
3637 const LayerVector& layers( mDrawingState.layersSortedByZ );
3638 const size_t count = layers.size();
3639 for (size_t i=0 ; i<count ; ++i) {
3640 const sp<Layer>& layer(layers[i]);
3641 const Layer::State& state(layer->getDrawingState());
3642 const bool visible = (state.layerStack == hw->getLayerStack())
3643 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3644 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003645 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003646 visible ? '+' : '-',
3647 i, layer->getName().string(), state.layerStack, state.z,
3648 layer->isVisible(), state.flags, state.alpha);
3649 }
3650 }
3651}
3652
Pablo Ceballosce796e72016-02-04 19:10:51 -08003653bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3654 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3655 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3656}
3657
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003658// ---------------------------------------------------------------------------
3659
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003660SurfaceFlinger::LayerVector::LayerVector() {
3661}
3662
3663SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003664 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003665}
3666
3667int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3668 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003669{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003670 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003671 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3672 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003673
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003674 uint32_t ls = l->getCurrentState().layerStack;
3675 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003676 if (ls != rs)
3677 return ls - rs;
3678
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003679 uint32_t lz = l->getCurrentState().z;
3680 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003681 if (lz != rz)
3682 return lz - rz;
3683
3684 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003685}
3686
3687// ---------------------------------------------------------------------------
3688
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003689SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003690 : type(DisplayDevice::DISPLAY_ID_INVALID),
3691 layerStack(DisplayDevice::NO_LAYER_STACK),
3692 orientation(0),
3693 width(0),
3694 height(0),
3695 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003696}
3697
Pablo Ceballos53390e12015-08-04 11:25:59 -07003698SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3699 DisplayDevice::DisplayType type, bool isSecure)
3700 : type(type),
3701 layerStack(DisplayDevice::NO_LAYER_STACK),
3702 orientation(0),
3703 width(0),
3704 height(0),
3705 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003706 viewport.makeInvalid();
3707 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003708}
3709
3710// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003712}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003713
3714
3715#if defined(__gl_h_)
3716#error "don't include gl/gl.h in this file"
3717#endif
3718
3719#if defined(__gl2_h_)
3720#error "don't include gl2/gl2.h in this file"
3721#endif