blob: a4e356891e121e38dddba969e863b83c5c9d6293 [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
Evgenii Stepanov22819272016-07-14 14:17:24 -070093// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
94// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
95// suppressed and prevents the device from booting.
96#ifndef __has_feature
97#define __has_feature(x) 0
98#endif
99#if __has_feature(address_sanitizer)
100__attribute__((visibility("default")))
101extern "C" const char* __asan_default_options() {
102 return "alloc_dealloc_mismatch=0";
103}
104#endif
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108// This is the phase offset in nanoseconds of the software vsync event
109// relative to the vsync event reported by HWComposer. The software vsync
110// event is when SurfaceFlinger and Choreographer-based applications run each
111// frame.
112//
113// This phase offset allows adjustment of the minimum latency from application
114// wake-up (by Choregographer) time to the time at which the resulting window
115// image is displayed. This value may be either positive (after the HW vsync)
116// or negative (before the HW vsync). Setting it to 0 will result in a
117// minimum latency of two vsync periods because the app and SurfaceFlinger
118// will run just after the HW vsync. Setting it to a positive number will
119// result in the minimum latency being:
120//
121// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
122//
123// Note that reducing this latency makes it more likely for the applications
124// to not have their window content image ready in time. When this happens
125// the latency will end up being an additional vsync period, and animations
126// will hiccup. Therefore, this latency should be tuned somewhat
127// conservatively (or at least with awareness of the trade-off being made).
128static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
129
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700130// This is the phase offset at which SurfaceFlinger's composition runs.
131static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133// ---------------------------------------------------------------------------
134
Mathias Agopian99b49842011-06-27 16:05:52 -0700135const String16 sHardwareTest("android.permission.HARDWARE_TEST");
136const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
137const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
138const String16 sDump("android.permission.DUMP");
139
140// ---------------------------------------------------------------------------
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700143 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700145 mTransactionPending(false),
146 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700147 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700149 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800151 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800154 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700156 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700157 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700158 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700163 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700164 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000165 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700166 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700167 mHWVsyncAvailable(false),
Alan Viverette9c5a3332013-09-12 20:04:35 -0700168 mDaltonize(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800169 mHasColorMatrix(false),
170 mHasPoweredOff(false),
171 mFrameBuckets(),
172 mTotalTime(0),
173 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174{
Steve Blocka19954a2012-01-04 20:05:49 +0000175 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800176
177 // debugging stuff...
178 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700179
Mathias Agopianb4b17302013-03-20 18:36:41 -0700180 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700181 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700182
Dan Stoza14cd37c2015-07-09 12:43:33 -0700183 property_get("debug.sf.drop_missed_frames", value, "0");
184 mDropMissedFrames = atoi(value);
185
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800186 property_get("debug.sf.showupdates", value, "0");
187 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700188
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700189 property_get("debug.sf.ddms", value, "0");
190 mDebugDDMS = atoi(value);
191 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700192 if (!startDdmConnection()) {
193 // start failed, and DDMS debugging not enabled
194 mDebugDDMS = 0;
195 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700196 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700197 ALOGI_IF(mDebugRegion, "showupdates enabled");
198 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800199}
200
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800201void SurfaceFlinger::onFirstRef()
202{
203 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800204}
205
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800206SurfaceFlinger::~SurfaceFlinger()
207{
Mathias Agopiana4912602012-07-12 14:25:33 -0700208 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
209 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
210 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800211}
212
Dan Stozac7014012014-02-14 15:03:43 -0800213void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800214{
215 // the window manager died on us. prepare its eulogy.
216
Andy McFadden13a082e2012-08-24 10:16:42 -0700217 // restore initial conditions (default device unblank, etc)
218 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800219
220 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700221 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800222}
223
Mathias Agopian7e27f052010-05-28 14:22:23 -0700224sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225{
Mathias Agopian96f08192010-06-02 23:28:45 -0700226 sp<ISurfaceComposerClient> bclient;
227 sp<Client> client(new Client(this));
228 status_t err = client->initCheck();
229 if (err == NO_ERROR) {
230 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232 return bclient;
233}
234
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700235sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
236 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700237{
238 class DisplayToken : public BBinder {
239 sp<SurfaceFlinger> flinger;
240 virtual ~DisplayToken() {
241 // no more references, this display must be terminated
242 Mutex::Autolock _l(flinger->mStateLock);
243 flinger->mCurrentState.displays.removeItem(this);
244 flinger->setTransactionFlags(eDisplayTransactionNeeded);
245 }
246 public:
247 DisplayToken(const sp<SurfaceFlinger>& flinger)
248 : flinger(flinger) {
249 }
250 };
251
252 sp<BBinder> token = new DisplayToken(this);
253
254 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700255 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700256 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700257 mCurrentState.displays.add(token, info);
258
259 return token;
260}
261
Jesse Hall6c913be2013-08-08 12:15:49 -0700262void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
263 Mutex::Autolock _l(mStateLock);
264
265 ssize_t idx = mCurrentState.displays.indexOfKey(display);
266 if (idx < 0) {
267 ALOGW("destroyDisplay: invalid display token");
268 return;
269 }
270
271 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
272 if (!info.isVirtualDisplay()) {
273 ALOGE("destroyDisplay called for non-virtual display");
274 return;
275 }
276
277 mCurrentState.displays.removeItemsAt(idx);
278 setTransactionFlags(eDisplayTransactionNeeded);
279}
280
Jesse Hall692c7232012-11-08 15:41:56 -0800281void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800282 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800283 ALOGW_IF(mBuiltinDisplays[type],
284 "Overwriting display token for display type %d", type);
285 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800286 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700287 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800288 mCurrentState.displays.add(mBuiltinDisplays[type], info);
289}
290
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700292 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
294 return NULL;
295 }
Jesse Hall692c7232012-11-08 15:41:56 -0800296 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297}
298
Jamie Gennis9a78c902011-01-12 18:30:40 -0800299sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
300{
301 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
302 return gba;
303}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700304
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800305void SurfaceFlinger::bootFinished()
306{
307 const nsecs_t now = systemTime();
308 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000309 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700310 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700311
312 // wait patiently for the window manager death
313 const String16 name("window");
314 sp<IBinder> window(defaultServiceManager()->getService(name));
315 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700316 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700317 }
318
319 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700320 // formerly we would just kill the process, but we now ask it to exit so it
321 // can choose where to stop the animation.
322 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700323
324 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
325 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
326 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327}
328
Mathias Agopian3f844832013-08-07 21:24:32 -0700329void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700330 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700331 RenderEngine& engine;
332 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700333 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700334 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
335 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700336 }
337 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700338 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700339 return true;
340 }
341 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700342 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700343}
344
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700345class DispSyncSource : public VSyncSource, private DispSync::Callback {
346public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700347 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000348 const char* name) :
349 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700350 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700351 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000352 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
353 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700354 mDispSync(dispSync),
355 mCallbackMutex(),
356 mCallback(),
357 mVsyncMutex(),
358 mPhaseOffset(phaseOffset),
359 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700360
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 virtual ~DispSyncSource() {}
362
363 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700364 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000366 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 static_cast<DispSync::Callback*>(this));
368 if (err != NO_ERROR) {
369 ALOGE("error registering vsync callback: %s (%d)",
370 strerror(-err), err);
371 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700372 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700373 } else {
374 status_t err = mDispSync->removeEventListener(
375 static_cast<DispSync::Callback*>(this));
376 if (err != NO_ERROR) {
377 ALOGE("error unregistering vsync callback: %s (%d)",
378 strerror(-err), err);
379 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700380 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700381 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700382 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700383 }
384
385 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700386 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700387 mCallback = callback;
388 }
389
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700390 virtual void setPhaseOffset(nsecs_t phaseOffset) {
391 Mutex::Autolock lock(mVsyncMutex);
392
393 // Normalize phaseOffset to [0, period)
394 auto period = mDispSync->getPeriod();
395 phaseOffset %= period;
396 if (phaseOffset < 0) {
397 // If we're here, then phaseOffset is in (-period, 0). After this
398 // operation, it will be in (0, period)
399 phaseOffset += period;
400 }
401 mPhaseOffset = phaseOffset;
402
403 // If we're not enabled, we don't need to mess with the listeners
404 if (!mEnabled) {
405 return;
406 }
407
408 // Remove the listener with the old offset
409 status_t err = mDispSync->removeEventListener(
410 static_cast<DispSync::Callback*>(this));
411 if (err != NO_ERROR) {
412 ALOGE("error unregistering vsync callback: %s (%d)",
413 strerror(-err), err);
414 }
415
416 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000417 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700418 static_cast<DispSync::Callback*>(this));
419 if (err != NO_ERROR) {
420 ALOGE("error registering vsync callback: %s (%d)",
421 strerror(-err), err);
422 }
423 }
424
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425private:
426 virtual void onDispSyncEvent(nsecs_t when) {
427 sp<VSyncSource::Callback> callback;
428 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700429 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 callback = mCallback;
431
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 if (mTraceVsync) {
433 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700434 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700435 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 }
437
438 if (callback != NULL) {
439 callback->onVSyncEvent(when);
440 }
441 }
442
Tim Murray4a4e4a22016-04-19 16:29:23 +0000443 const char* const mName;
444
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700445 int mValue;
446
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700447 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700448 const String8 mVsyncOnLabel;
449 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700450
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700451 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700452
453 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700455
456 Mutex mVsyncMutex; // Protects the following
457 nsecs_t mPhaseOffset;
458 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700459};
460
461void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700462 ALOGI( "SurfaceFlinger's main thread ready to run. "
463 "Initializing graphics H/W...");
464
Dan Stoza9e56aa02015-11-02 13:00:03 -0800465 { // Autolock scope
466 Mutex::Autolock _l(mStateLock);
467
468 // initialize EGL for the default display
469 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
470 eglInitialize(mEGLDisplay, NULL, NULL);
471
472 // start the EventThread
473 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
474 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000475 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800476 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
477 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000478 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800479 mEventQueue.setEventThread(mSFEventThread);
480
481 // Get a RenderEngine for the given display / config (can't fail)
482 mRenderEngine = RenderEngine::create(mEGLDisplay,
483 HAL_PIXEL_FORMAT_RGBA_8888);
484 }
485
486 // Drop the state lock while we initialize the hardware composer. We drop
487 // the lock because on creation, it will call back into SurfaceFlinger to
488 // initialize the primary display.
489 mHwc = new HWComposer(this);
490 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
491
Jesse Hall692c7232012-11-08 15:41:56 -0800492 Mutex::Autolock _l(mStateLock);
493
Mathias Agopian875d8e12013-06-07 15:35:48 -0700494 // retrieve the EGL context that was selected/created
495 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700496
Mathias Agopianda27af92012-09-13 18:17:13 -0700497 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
498 "couldn't create EGLContext");
499
Dan Stoza9e56aa02015-11-02 13:00:03 -0800500 // make the GLContext current so that we can create textures when creating
501 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700502 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
503
Jamie Gennisd1700752013-10-14 12:22:52 -0700504 mEventControlThread = new EventControlThread(this);
505 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
506
Mathias Agopian92a979a2012-08-02 18:32:23 -0700507 // initialize our drawing state
508 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700509
Andy McFadden13a082e2012-08-24 10:16:42 -0700510 // set initial conditions (e.g. unblank default device)
511 initializeDisplays();
512
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700513 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700514 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515
Dan Stoza9e56aa02015-11-02 13:00:03 -0800516 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700517}
518
Mathias Agopiana67e4182012-06-19 17:26:12 -0700519void SurfaceFlinger::startBootAnim() {
520 // start boot animation
521 property_set("service.bootanim.exit", "0");
522 property_set("ctl.start", "bootanim");
523}
524
Mathias Agopian875d8e12013-06-07 15:35:48 -0700525size_t SurfaceFlinger::getMaxTextureSize() const {
526 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700527}
528
Mathias Agopian875d8e12013-06-07 15:35:48 -0700529size_t SurfaceFlinger::getMaxViewportDims() const {
530 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700531}
532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800534
Jamie Gennis582270d2011-08-17 18:19:00 -0700535bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800536 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800537 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800538 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700539 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800540}
541
Dan Stoza7f7da322014-05-02 15:26:25 -0700542status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
543 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700544 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700545 return BAD_VALUE;
546 }
547
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500548 if (!display.get())
549 return NAME_NOT_FOUND;
550
Jesse Hall692c7232012-11-08 15:41:56 -0800551 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700552 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800553 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700554 type = i;
555 break;
556 }
557 }
558
559 if (type < 0) {
560 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700561 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700562
Mathias Agopian8b736f12012-08-13 17:54:26 -0700563 // TODO: Not sure if display density should handled by SF any longer
564 class Density {
565 static int getDensityFromProperty(char const* propName) {
566 char property[PROPERTY_VALUE_MAX];
567 int density = 0;
568 if (property_get(propName, property, NULL) > 0) {
569 density = atoi(property);
570 }
571 return density;
572 }
573 public:
574 static int getEmuDensity() {
575 return getDensityFromProperty("qemu.sf.lcd_density"); }
576 static int getBuildDensity() {
577 return getDensityFromProperty("ro.sf.lcd_density"); }
578 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700579
Dan Stoza7f7da322014-05-02 15:26:25 -0700580 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700581
Dan Stoza9e56aa02015-11-02 13:00:03 -0800582 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700583 DisplayInfo info = DisplayInfo();
584
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585 float xdpi = hwConfig->getDpiX();
586 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700587
588 if (type == DisplayDevice::DISPLAY_PRIMARY) {
589 // The density of the device is provided by a build property
590 float density = Density::getBuildDensity() / 160.0f;
591 if (density == 0) {
592 // the build doesn't provide a density -- this is wrong!
593 // use xdpi instead
594 ALOGE("ro.sf.lcd_density must be defined as a build property");
595 density = xdpi / 160.0f;
596 }
597 if (Density::getEmuDensity()) {
598 // if "qemu.sf.lcd_density" is specified, it overrides everything
599 xdpi = ydpi = density = Density::getEmuDensity();
600 density /= 160.0f;
601 }
602 info.density = density;
603
604 // TODO: this needs to go away (currently needed only by webkit)
605 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
606 info.orientation = hw->getOrientation();
607 } else {
608 // TODO: where should this value come from?
609 static const int TV_DENSITY = 213;
610 info.density = TV_DENSITY / 160.0f;
611 info.orientation = 0;
612 }
613
Dan Stoza9e56aa02015-11-02 13:00:03 -0800614 info.w = hwConfig->getWidth();
615 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700616 info.xdpi = xdpi;
617 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800618 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700619 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620
621 // TODO: Hook this back up
622 info.colorTransform = 0;
Andy McFadden91b2ca82014-06-13 14:04:23 -0700623
624 // This is how far in advance a buffer must be queued for
625 // presentation at a given time. If you want a buffer to appear
626 // on the screen at time N, you must submit the buffer before
627 // (N - presentationDeadline).
628 //
629 // Normally it's one full refresh period (to give SF a chance to
630 // latch the buffer), but this can be reduced by configuring a
631 // DispSync offset. Any additional delays introduced by the hardware
632 // composer or panel must be accounted for here.
633 //
634 // We add an additional 1ms to allow for processing time and
635 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800636 info.presentationDeadline = hwConfig->getVsyncPeriod() -
637 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700638
639 // All non-virtual displays are currently considered secure.
640 info.secure = true;
641
642 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700643 }
644
Dan Stoza7f7da322014-05-02 15:26:25 -0700645 return NO_ERROR;
646}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700647
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800648status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700649 DisplayStatInfo* stats) {
650 if (stats == NULL) {
651 return BAD_VALUE;
652 }
653
654 // FIXME for now we always return stats for the primary display
655 memset(stats, 0, sizeof(*stats));
656 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
657 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
658 return NO_ERROR;
659}
660
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700661int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700662 sp<DisplayDevice> device(getDisplayDevice(display));
663 if (device != NULL) {
664 return device->getActiveConfig();
665 }
666 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700667}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700668
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700669void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
670 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
671 this);
672 int32_t type = hw->getDisplayType();
673 int currentMode = hw->getActiveConfig();
674
675 if (mode == currentMode) {
676 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
677 return;
678 }
679
680 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
681 ALOGW("Trying to set config for virtual display");
682 return;
683 }
684
685 hw->setActiveConfig(mode);
686 getHwComposer().setActiveConfig(type, mode);
687}
688
689status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
690 class MessageSetActiveConfig: public MessageBase {
691 SurfaceFlinger& mFlinger;
692 sp<IBinder> mDisplay;
693 int mMode;
694 public:
695 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
696 int mode) :
697 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
698 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700699 Vector<DisplayInfo> configs;
700 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700701 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700702 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700703 mMode, configs.size());
704 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700705 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
706 if (hw == NULL) {
707 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700708 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700709 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
710 ALOGW("Attempt to set active config = %d for virtual display",
711 mMode);
712 } else {
713 mFlinger.setActiveConfigInternal(hw, mMode);
714 }
715 return true;
716 }
717 };
718 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
719 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700720 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700721}
722
Svetoslavd85084b2014-03-20 10:28:31 -0700723status_t SurfaceFlinger::clearAnimationFrameStats() {
724 Mutex::Autolock _l(mStateLock);
725 mAnimFrameTracker.clearStats();
726 return NO_ERROR;
727}
728
729status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
730 Mutex::Autolock _l(mStateLock);
731 mAnimFrameTracker.getStats(outStats);
732 return NO_ERROR;
733}
734
Dan Stozac4f471e2016-03-24 09:31:08 -0700735status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
736 HdrCapabilities* outCapabilities) const {
737 Mutex::Autolock _l(mStateLock);
738
739 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
740 if (displayDevice == nullptr) {
741 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
742 return BAD_VALUE;
743 }
744
745 std::unique_ptr<HdrCapabilities> capabilities =
746 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
747 if (capabilities) {
748 std::swap(*outCapabilities, *capabilities);
749 } else {
750 return BAD_VALUE;
751 }
752
753 return NO_ERROR;
754}
755
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800756// ----------------------------------------------------------------------------
757
758sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800759 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700760}
761
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800762// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800763
764void SurfaceFlinger::waitForEvent() {
765 mEventQueue.waitMessage();
766}
767
768void SurfaceFlinger::signalTransaction() {
769 mEventQueue.invalidate();
770}
771
772void SurfaceFlinger::signalLayerUpdate() {
773 mEventQueue.invalidate();
774}
775
776void SurfaceFlinger::signalRefresh() {
777 mEventQueue.refresh();
778}
779
780status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800781 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800782 return mEventQueue.postMessage(msg, reltime);
783}
784
785status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800786 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800787 status_t res = mEventQueue.postMessage(msg, reltime);
788 if (res == NO_ERROR) {
789 msg->wait();
790 }
791 return res;
792}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800793
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700794void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700795 do {
796 waitForEvent();
797 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800798}
799
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700800void SurfaceFlinger::enableHardwareVsync() {
801 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700802 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700803 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700804 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
805 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700806 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700807 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700808}
809
Jesse Hall948fe0c2013-10-14 12:56:09 -0700810void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700811 Mutex::Autolock _l(mHWVsyncLock);
812
Jesse Hall948fe0c2013-10-14 12:56:09 -0700813 if (makeAvailable) {
814 mHWVsyncAvailable = true;
815 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700816 // Hardware vsync is not currently available, so abort the resync
817 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700818 return;
819 }
820
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
822 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700823
824 mPrimaryDispSync.reset();
825 mPrimaryDispSync.setPeriod(period);
826
827 if (!mPrimaryHWVsyncEnabled) {
828 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700829 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
830 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700831 mPrimaryHWVsyncEnabled = true;
832 }
833}
834
Jesse Hall948fe0c2013-10-14 12:56:09 -0700835void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700836 Mutex::Autolock _l(mHWVsyncLock);
837 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700838 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
839 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700840 mPrimaryDispSync.endResync();
841 mPrimaryHWVsyncEnabled = false;
842 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700843 if (makeUnavailable) {
844 mHWVsyncAvailable = false;
845 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700846}
847
Tim Murray4a4e4a22016-04-19 16:29:23 +0000848void SurfaceFlinger::resyncWithRateLimit() {
849 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
850 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700851 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000852 }
853}
854
Dan Stoza9e56aa02015-11-02 13:00:03 -0800855void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700856 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700857
Jamie Gennisd1700752013-10-14 12:22:52 -0700858 { // Scope for the lock
859 Mutex::Autolock _l(mHWVsyncLock);
860 if (type == 0 && mPrimaryHWVsyncEnabled) {
861 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700862 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700863 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700864
865 if (needsHwVsync) {
866 enableHardwareVsync();
867 } else {
868 disableHardwareVsync(false);
869 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700870}
871
Dan Stoza9e56aa02015-11-02 13:00:03 -0800872void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
873 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
874 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
875 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700876
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877 // All non-virtual displays are currently considered secure.
878 bool isSecure = true;
879
880 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
881 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
882 wp<IBinder> token = mBuiltinDisplays[type];
883
884 sp<IGraphicBufferProducer> producer;
885 sp<IGraphicBufferConsumer> consumer;
886 BufferQueue::createBufferQueue(&producer, &consumer,
887 new GraphicBufferAlloc());
888
889 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
890 DisplayDevice::DISPLAY_PRIMARY, consumer);
891 sp<DisplayDevice> hw = new DisplayDevice(this,
892 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
893 producer, mRenderEngine->getEGLConfig());
894 mDisplays.add(token, hw);
895 } else {
896 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700897 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800898 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800899 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700900 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800901 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
902 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700903 }
904 setTransactionFlags(eDisplayTransactionNeeded);
905
Andy McFadden9e9689c2012-10-10 18:17:51 -0700906 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700907 }
Mathias Agopian86303202012-07-24 22:46:10 -0700908}
909
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700911 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800912 getHwComposer().setVsyncEnabled(disp,
913 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700914}
915
Mathias Agopian4fec8732012-06-29 14:12:52 -0700916void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800917 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800918 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800919 case MessageQueue::INVALIDATE: {
920 bool refreshNeeded = handleMessageTransaction();
921 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800922 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800923 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800924 // Signal a refresh if a transaction modified the window state,
925 // a new buffer was latched, or if HWC has requested a full
926 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800927 signalRefresh();
928 }
929 break;
930 }
931 case MessageQueue::REFRESH: {
932 handleMessageRefresh();
933 break;
934 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800935 }
936}
937
Dan Stoza6b9454d2014-11-07 16:00:59 -0800938bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700939 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700940 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700941 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800942 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700943 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800944 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700945}
946
Dan Stoza6b9454d2014-11-07 16:00:59 -0800947bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700948 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800949 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700950}
951
952void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700953 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700954
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700955#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -0800956 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700957#else
958 nsecs_t refreshStartTime = 0;
959#endif
Dan Stoza14cd37c2015-07-09 12:43:33 -0700960 static nsecs_t previousExpectedPresent = 0;
961 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
962 static bool previousFrameMissed = false;
963 bool frameMissed = (expectedPresent == previousExpectedPresent);
964 if (frameMissed != previousFrameMissed) {
965 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
966 }
967 previousFrameMissed = frameMissed;
968
969 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
970 // Latch buffers, but don't send anything to HWC, then signal another
971 // wakeup for the next vsync
972 preComposition();
973 repaintEverything();
974 } else {
975 preComposition();
976 rebuildLayerStacks();
977 setUpHWComposer();
978 doDebugFlashRegions();
979 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800980 postComposition(refreshStartTime);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700981 }
982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983 // Release any buffers which were replaced this frame
984 for (auto& layer : mLayersWithQueuedFrames) {
985 layer->releasePendingBuffer();
986 }
987 mLayersWithQueuedFrames.clear();
988
Dan Stoza14cd37c2015-07-09 12:43:33 -0700989 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
Mathias Agopiancd60f992012-08-16 16:28:27 -0700990}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700991
Mathias Agopiancd60f992012-08-16 16:28:27 -0700992void SurfaceFlinger::doDebugFlashRegions()
993{
994 // is debugging enabled
995 if (CC_LIKELY(!mDebugRegion))
996 return;
997
998 const bool repaintEverything = mRepaintEverything;
999 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1000 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001001 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001002 // transform the dirty region into this screen's coordinate space
1003 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1004 if (!dirtyRegion.isEmpty()) {
1005 // redraw the whole screen
1006 doComposeSurfaces(hw, Region(hw->bounds()));
1007
1008 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001009 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001010 RenderEngine& engine(getRenderEngine());
1011 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1012
Mathias Agopianda27af92012-09-13 18:17:13 -07001013 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001014 }
1015 }
1016 }
1017
1018 postFramebuffer();
1019
1020 if (mDebugRegion > 1) {
1021 usleep(mDebugRegion * 1000);
1022 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001023
Dan Stoza9e56aa02015-11-02 13:00:03 -08001024 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza00ac3592016-06-17 11:29:01 -07001025 auto& displayDevice = mDisplays[displayId];
1026 if (!displayDevice->isDisplayOn()) {
1027 continue;
1028 }
1029
1030 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001031 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1032 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001033 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001034}
1035
1036void SurfaceFlinger::preComposition()
1037{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001038 ATRACE_CALL();
1039 ALOGV("preComposition");
1040
Mathias Agopiancd60f992012-08-16 16:28:27 -07001041 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001042 const LayerVector& layers(mDrawingState.layersSortedByZ);
1043 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001044 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001045 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001046 needExtraInvalidate = true;
1047 }
1048 }
1049 if (needExtraInvalidate) {
1050 signalLayerUpdate();
1051 }
1052}
1053
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001054#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001055void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001056#else
1057void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1058#endif
Mathias Agopiancd60f992012-08-16 16:28:27 -07001059{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001060 ATRACE_CALL();
1061 ALOGV("postComposition");
1062
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001063 const LayerVector& layers(mDrawingState.layersSortedByZ);
1064 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001065 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001066 layers[i]->onPostComposition();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001067 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001068
Dan Stoza9e56aa02015-11-02 13:00:03 -08001069 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070
1071 if (presentFence->isValid()) {
1072 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1073 enableHardwareVsync();
1074 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001075 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 }
1077 }
1078
Dan Stozab90cf072015-03-05 11:05:59 -08001079 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001080 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001081 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 enableHardwareVsync();
1083 }
1084 }
1085
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001086#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001087 mFenceTracker.addFrame(refreshStartTime, presentFence,
1088 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001089#endif
Pablo Ceballos40845df2016-01-25 17:41:15 -08001090
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001091 if (mAnimCompositionPending) {
1092 mAnimCompositionPending = false;
1093
Jesse Halla9a1b002013-02-27 16:39:25 -08001094 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001095 mAnimFrameTracker.setActualPresentFence(presentFence);
1096 } else {
1097 // The HWC doesn't support present fences, so use the refresh
1098 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001099 nsecs_t presentTime =
1100 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001101 mAnimFrameTracker.setActualPresentTime(presentTime);
1102 }
1103 mAnimFrameTracker.advanceFrame();
1104 }
Dan Stozab90cf072015-03-05 11:05:59 -08001105
1106 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1107 return;
1108 }
1109
1110 nsecs_t currentTime = systemTime();
1111 if (mHasPoweredOff) {
1112 mHasPoweredOff = false;
1113 } else {
1114 nsecs_t period = mPrimaryDispSync.getPeriod();
1115 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1116 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1117 if (numPeriods < NUM_BUCKETS - 1) {
1118 mFrameBuckets[numPeriods] += elapsedTime;
1119 } else {
1120 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1121 }
1122 mTotalTime += elapsedTime;
1123 }
1124 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001125}
1126
1127void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001128 ATRACE_CALL();
1129 ALOGV("rebuildLayerStacks");
1130
Mathias Agopiancd60f992012-08-16 16:28:27 -07001131 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001132 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001133 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001134 mVisibleRegionsDirty = false;
1135 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001136
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001137 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001138 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001139 Region opaqueRegion;
1140 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 Vector<sp<Layer>> layersSortedByZ;
1142 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1143 const Transform& tr(displayDevice->getTransform());
1144 const Rect bounds(displayDevice->getBounds());
1145 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001146 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001147 displayDevice->getLayerStack(), dirtyRegion,
1148 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001149
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001150 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001151 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001152 const sp<Layer>& layer(layers[i]);
1153 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001154 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001155 Region drawRegion(tr.transform(
1156 layer->visibleNonTransparentRegion));
1157 drawRegion.andSelf(bounds);
1158 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001159 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001160 } else {
1161 // Clear out the HWC layer if this layer was
1162 // previously visible, but no longer is
1163 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1164 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001165 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001166 }
1167 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001168 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001169 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1170 displayDevice->undefinedRegion.set(bounds);
1171 displayDevice->undefinedRegion.subtractSelf(
1172 tr.transform(opaqueRegion));
1173 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001174 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001175 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001176}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001177
Mathias Agopiancd60f992012-08-16 16:28:27 -07001178void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001179 ATRACE_CALL();
1180 ALOGV("setUpHWComposer");
1181
Jesse Hall028dc8f2013-08-20 16:35:32 -07001182 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001183 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1184 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1185 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1186
1187 // If nothing has changed (!dirty), don't recompose.
1188 // If something changed, but we don't currently have any visible layers,
1189 // and didn't when we last did a composition, then skip it this time.
1190 // The second rule does two things:
1191 // - When all layers are removed from a display, we'll emit one black
1192 // frame, then nothing more until we get new layers.
1193 // - When a display is created with a private layer stack, we won't
1194 // emit any black frames until a layer is added to the layer stack.
1195 bool mustRecompose = dirty && !(empty && wasEmpty);
1196
1197 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1198 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1199 mustRecompose ? "doing" : "skipping",
1200 dirty ? "+" : "-",
1201 empty ? "+" : "-",
1202 wasEmpty ? "+" : "-");
1203
Dan Stoza71433162014-02-04 16:22:36 -08001204 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001205
1206 if (mustRecompose) {
1207 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1208 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001209 }
1210
Dan Stoza9e56aa02015-11-02 13:00:03 -08001211 // build the h/w work list
1212 if (CC_UNLIKELY(mGeometryInvalid)) {
1213 mGeometryInvalid = false;
1214 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1215 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1216 const auto hwcId = displayDevice->getHwcDisplayId();
1217 if (hwcId >= 0) {
1218 const Vector<sp<Layer>>& currentLayers(
1219 displayDevice->getVisibleLayersSortedByZ());
1220 bool foundLayerWithoutHwc = false;
1221 for (auto& layer : currentLayers) {
1222 if (!layer->hasHwcLayer(hwcId)) {
1223 auto hwcLayer = mHwc->createLayer(hwcId);
1224 if (hwcLayer) {
1225 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1226 } else {
1227 layer->forceClientComposition(hwcId);
1228 foundLayerWithoutHwc = true;
1229 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001230 }
1231 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001232
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 layer->setGeometry(displayDevice);
1234 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1235 mHasColorMatrix) {
1236 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001237 }
1238 }
1239 }
1240 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241 }
Riley Andrews03414a12014-07-01 14:22:59 -07001242
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 // Set the per-frame data
1244 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1245 auto& displayDevice = mDisplays[displayId];
1246 const auto hwcId = displayDevice->getHwcDisplayId();
1247 if (hwcId < 0) {
1248 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001249 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1251 layer->setPerFrameData(displayDevice);
1252 }
1253 }
1254
1255 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza00ac3592016-06-17 11:29:01 -07001256 auto& displayDevice = mDisplays[displayId];
1257 if (!displayDevice->isDisplayOn()) {
1258 continue;
1259 }
1260
1261 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001262 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1263 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001264 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001265}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001266
Mathias Agopiancd60f992012-08-16 16:28:27 -07001267void SurfaceFlinger::doComposition() {
1268 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001269 ALOGV("doComposition");
1270
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001271 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001272 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001273 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001274 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001275 // transform the dirty region into this screen's coordinate space
1276 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001277
1278 // repaint the framebuffer (if needed)
1279 doDisplayComposition(hw, dirtyRegion);
1280
Mathias Agopiancd60f992012-08-16 16:28:27 -07001281 hw->dirtyRegion.clear();
1282 hw->flip(hw->swapRegion);
1283 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001284 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001285 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001286 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001287}
1288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001289void SurfaceFlinger::postFramebuffer()
1290{
Mathias Agopian841cde52012-03-01 15:44:37 -08001291 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001292 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001293
Mathias Agopiana44b0412011-10-16 18:46:35 -07001294 const nsecs_t now = systemTime();
1295 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001296
Dan Stoza9e56aa02015-11-02 13:00:03 -08001297 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1298 auto& displayDevice = mDisplays[displayId];
Dan Stoza00ac3592016-06-17 11:29:01 -07001299 if (!displayDevice->isDisplayOn()) {
1300 continue;
1301 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 const auto hwcId = displayDevice->getHwcDisplayId();
1303 if (hwcId >= 0) {
1304 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001305 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001306 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 if (displayId == 0) {
1308 // Make the default display current because the VirtualDisplayDevice
1309 // code cannot deal with dequeueBuffer() being called outside of the
1310 // composition loop; however the code below can call glFlush() which
1311 // is allowed to (and does in some case) call dequeueBuffer().
1312 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1313 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001314 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1315 sp<Fence> releaseFence = Fence::NO_FENCE;
1316 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1317 releaseFence = displayDevice->getClientTargetAcquireFence();
1318 } else {
1319 auto hwcLayer = layer->getHwcLayer(hwcId);
1320 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001321 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001322 layer->onLayerDisplayed(releaseFence);
1323 }
1324 if (hwcId >= 0) {
1325 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001326 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001327 }
1328
Mathias Agopiana44b0412011-10-16 18:46:35 -07001329 mLastSwapBufferTime = systemTime() - now;
1330 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001331
1332 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1333 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1334 logFrameStats();
1335 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001336}
1337
Mathias Agopian87baae12012-07-31 12:38:26 -07001338void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001339{
Mathias Agopian841cde52012-03-01 15:44:37 -08001340 ATRACE_CALL();
1341
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001342 // here we keep a copy of the drawing state (that is the state that's
1343 // going to be overwritten by handleTransactionLocked()) outside of
1344 // mStateLock so that the side-effects of the State assignment
1345 // don't happen with mStateLock held (which can cause deadlocks).
1346 State drawingState(mDrawingState);
1347
Mathias Agopianca4d3602011-05-19 15:38:14 -07001348 Mutex::Autolock _l(mStateLock);
1349 const nsecs_t now = systemTime();
1350 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001351
Mathias Agopianca4d3602011-05-19 15:38:14 -07001352 // Here we're guaranteed that some transaction flags are set
1353 // so we can call handleTransactionLocked() unconditionally.
1354 // We call getTransactionFlags(), which will also clear the flags,
1355 // with mStateLock held to guarantee that mCurrentState won't change
1356 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001357
Mathias Agopiane57f2922012-08-09 16:29:12 -07001358 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001359 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001360
Mathias Agopianca4d3602011-05-19 15:38:14 -07001361 mLastTransactionTime = systemTime() - now;
1362 mDebugInTransaction = 0;
1363 invalidateHwcGeometry();
1364 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001365}
1366
Mathias Agopian87baae12012-07-31 12:38:26 -07001367void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001368{
1369 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370 const size_t count = currentLayers.size();
1371
Dan Stoza7dde5992015-05-22 09:51:44 -07001372 // Notify all layers of available frames
1373 for (size_t i = 0; i < count; ++i) {
1374 currentLayers[i]->notifyAvailableFrames();
1375 }
1376
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001377 /*
1378 * Traversal of the children
1379 * (perform the transaction for each of them if needed)
1380 */
1381
Mathias Agopian3559b072012-08-15 13:46:03 -07001382 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001383 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001384 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001385 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1386 if (!trFlags) continue;
1387
1388 const uint32_t flags = layer->doTransaction(0);
1389 if (flags & Layer::eVisibleRegion)
1390 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001391 }
1392 }
1393
1394 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001395 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396 */
1397
Mathias Agopiane57f2922012-08-09 16:29:12 -07001398 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001399 // here we take advantage of Vector's copy-on-write semantics to
1400 // improve performance by skipping the transaction entirely when
1401 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001402 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1403 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001404 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001405 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001406 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001407 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001408
1409 // find the displays that were removed
1410 // (ie: in drawing state but not in current state)
1411 // also handle displays that changed
1412 // (ie: displays that are in both lists)
1413 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001414 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1415 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001416 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001417 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001418 // Call makeCurrent() on the primary display so we can
1419 // be sure that nothing associated with this display
1420 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001421 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001422 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001423 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1424 if (hw != NULL)
1425 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001426 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001427 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001428 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001429 } else {
1430 ALOGW("trying to remove the main display");
1431 }
1432 } else {
1433 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001434 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001435 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001436 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1437 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001438 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001439 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001440 // recreating the DisplayDevice, so we just remove it
1441 // from the drawing state, so that it get re-added
1442 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001443 sp<DisplayDevice> hw(getDisplayDevice(display));
1444 if (hw != NULL)
1445 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001446 mDisplays.removeItem(display);
1447 mDrawingState.displays.removeItemsAt(i);
1448 dc--; i--;
1449 // at this point we must loop to the next item
1450 continue;
1451 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001452
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001453 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001454 if (disp != NULL) {
1455 if (state.layerStack != draw[i].layerStack) {
1456 disp->setLayerStack(state.layerStack);
1457 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001458 if ((state.orientation != draw[i].orientation)
1459 || (state.viewport != draw[i].viewport)
1460 || (state.frame != draw[i].frame))
1461 {
1462 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001463 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001464 }
Michael Lentine47e45402014-07-18 15:34:25 -07001465 if (state.width != draw[i].width || state.height != draw[i].height) {
1466 disp->setDisplaySize(state.width, state.height);
1467 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001468 }
1469 }
1470 }
1471
1472 // find displays that were added
1473 // (ie: in current state but not in drawing state)
1474 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001475 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001476 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001477
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001478 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001479 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001480 sp<IGraphicBufferProducer> bqProducer;
1481 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001482 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1483 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001484
Dan Stoza9e56aa02015-11-02 13:00:03 -08001485 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001486 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001487 // Virtual displays without a surface are dormant:
1488 // they have external state (layer stack, projection,
1489 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001490 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001491
Dan Stoza1f3efb12014-10-15 16:34:55 -07001492 int width = 0;
1493 int status = state.surface->query(
1494 NATIVE_WINDOW_WIDTH, &width);
1495 ALOGE_IF(status != NO_ERROR,
1496 "Unable to query width (%d)", status);
1497 int height = 0;
1498 status = state.surface->query(
1499 NATIVE_WINDOW_HEIGHT, &height);
1500 ALOGE_IF(status != NO_ERROR,
1501 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001502 int intFormat = 0;
1503 status = state.surface->query(
1504 NATIVE_WINDOW_FORMAT, &intFormat);
1505 ALOGE_IF(status != NO_ERROR,
1506 "Unable to query format (%d)", status);
1507 auto format = static_cast<android_pixel_format_t>(
1508 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001509
Dan Stoza5cf424b2016-05-20 14:02:39 -07001510 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001511 &hwcId);
1512
Dan Stoza5cf424b2016-05-20 14:02:39 -07001513 // TODO: Plumb requested format back up to consumer
1514
Dan Stoza9e56aa02015-11-02 13:00:03 -08001515 sp<VirtualDisplaySurface> vds =
1516 new VirtualDisplaySurface(*mHwc,
1517 hwcId, state.surface, bqProducer,
1518 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001519
1520 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001521 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001522 }
1523 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001524 ALOGE_IF(state.surface!=NULL,
1525 "adding a supported display, but rendering "
1526 "surface is provided (%p), ignoring it",
1527 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001528 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1529 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1530 dispSurface = new FramebufferSurface(*mHwc,
1531 DisplayDevice::DISPLAY_EXTERNAL,
1532 bqConsumer);
1533 producer = bqProducer;
1534 } else {
1535 ALOGE("Attempted to add non-external non-virtual"
1536 " display");
1537 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001538 }
1539
1540 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001541 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001542 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001543 state.type, hwcId, state.isSecure, display,
1544 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001545 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001546 hw->setLayerStack(state.layerStack);
1547 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001548 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001549 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001550 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001551 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001552 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001553 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001554 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001555 }
1556 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001558 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001559
Mathias Agopian84300952012-11-21 16:02:13 -08001560 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1561 // The transform hint might have changed for some layers
1562 // (either because a display has changed, or because a layer
1563 // as changed).
1564 //
1565 // Walk through all the layers in currentLayers,
1566 // and update their transform hint.
1567 //
1568 // If a layer is visible only on a single display, then that
1569 // display is used to calculate the hint, otherwise we use the
1570 // default display.
1571 //
1572 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1573 // the hint is set before we acquire a buffer from the surface texture.
1574 //
1575 // NOTE: layer transactions have taken place already, so we use their
1576 // drawing state. However, SurfaceFlinger's own transaction has not
1577 // happened yet, so we must use the current state layer list
1578 // (soon to become the drawing state list).
1579 //
1580 sp<const DisplayDevice> disp;
1581 uint32_t currentlayerStack = 0;
1582 for (size_t i=0; i<count; i++) {
1583 // NOTE: we rely on the fact that layers are sorted by
1584 // layerStack first (so we don't have to traverse the list
1585 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001586 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001587 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001588 if (i==0 || currentlayerStack != layerStack) {
1589 currentlayerStack = layerStack;
1590 // figure out if this layerstack is mirrored
1591 // (more than one display) if so, pick the default display,
1592 // if not, pick the only display it's on.
1593 disp.clear();
1594 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1595 sp<const DisplayDevice> hw(mDisplays[dpy]);
1596 if (hw->getLayerStack() == currentlayerStack) {
1597 if (disp == NULL) {
1598 disp = hw;
1599 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001600 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001601 break;
1602 }
1603 }
1604 }
1605 }
Chet Haase91d25932013-04-11 15:24:55 -07001606 if (disp == NULL) {
1607 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1608 // redraw after transform hint changes. See bug 8508397.
1609
1610 // could be null when this layer is using a layerStack
1611 // that is not visible on any display. Also can occur at
1612 // screen off/on times.
1613 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001614 }
Chet Haase91d25932013-04-11 15:24:55 -07001615 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001616 }
1617 }
1618
1619
Mathias Agopian3559b072012-08-15 13:46:03 -07001620 /*
1621 * Perform our own transaction if needed
1622 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001623
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001624 const LayerVector& layers(mDrawingState.layersSortedByZ);
1625 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001626 // layers have been added
1627 mVisibleRegionsDirty = true;
1628 }
1629
1630 // some layers might have been removed, so
1631 // we need to update the regions they're exposing.
1632 if (mLayersRemoved) {
1633 mLayersRemoved = false;
1634 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001635 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001636 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001637 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001638 if (currentLayers.indexOf(layer) < 0) {
1639 // this layer is not visible anymore
1640 // TODO: we could traverse the tree from front to back and
1641 // compute the actual visible region
1642 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001643 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001644 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001645 Region(Rect(s.active.w, s.active.h)));
1646 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001649 }
1650
1651 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001652
1653 updateCursorAsync();
1654}
1655
1656void SurfaceFlinger::updateCursorAsync()
1657{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001658 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1659 auto& displayDevice = mDisplays[displayId];
1660 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001661 continue;
1662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663
1664 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1665 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001666 }
1667 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001668}
1669
1670void SurfaceFlinger::commitTransaction()
1671{
1672 if (!mLayersPendingRemoval.isEmpty()) {
1673 // Notify removed layers now that they can't be drawn from
1674 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1675 mLayersPendingRemoval[i]->onRemoved();
1676 }
1677 mLayersPendingRemoval.clear();
1678 }
1679
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001680 // If this transaction is part of a window animation then the next frame
1681 // we composite should be considered an animation as well.
1682 mAnimCompositionPending = mAnimTransactionPending;
1683
Mathias Agopian4fec8732012-06-29 14:12:52 -07001684 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001685 mTransactionPending = false;
1686 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001687 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001688}
1689
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001690void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001691 const LayerVector& currentLayers, uint32_t layerStack,
1692 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001693{
Mathias Agopian841cde52012-03-01 15:44:37 -08001694 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001697 Region aboveOpaqueLayers;
1698 Region aboveCoveredLayers;
1699 Region dirty;
1700
Mathias Agopian87baae12012-07-31 12:38:26 -07001701 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001702
1703 size_t i = currentLayers.size();
1704 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001705 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001706
1707 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001708 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709
Jesse Hall01e29052013-02-19 16:13:35 -08001710 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001711 if (s.layerStack != layerStack)
1712 continue;
1713
Mathias Agopianab028732010-03-16 16:41:46 -07001714 /*
1715 * opaqueRegion: area of a surface that is fully opaque.
1716 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001717 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001718
1719 /*
1720 * visibleRegion: area of a surface that is visible on screen
1721 * and not fully transparent. This is essentially the layer's
1722 * footprint minus the opaque regions above it.
1723 * Areas covered by a translucent surface are considered visible.
1724 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001726
1727 /*
1728 * coveredRegion: area of a surface that is covered by all
1729 * visible regions above it (which includes the translucent areas).
1730 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001731 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001732
Jesse Halla8026d22012-09-25 13:25:04 -07001733 /*
1734 * transparentRegion: area of a surface that is hinted to be completely
1735 * transparent. This is only used to tell when the layer has no visible
1736 * non-transparent regions and can be removed from the layer list. It
1737 * does not affect the visibleRegion of this layer or any layers
1738 * beneath it. The hint may not be correct if apps don't respect the
1739 * SurfaceView restrictions (which, sadly, some don't).
1740 */
1741 Region transparentRegion;
1742
Mathias Agopianab028732010-03-16 16:41:46 -07001743
1744 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001745 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001746 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001747 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001748 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001749 if (!visibleRegion.isEmpty()) {
1750 // Remove the transparent area from the visible region
1751 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001752 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001753 if (tr.preserveRects()) {
1754 // transform the transparent region
1755 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001756 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001757 // transformation too complex, can't do the
1758 // transparent region optimization.
1759 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001760 }
Mathias Agopianab028732010-03-16 16:41:46 -07001761 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001762
Mathias Agopianab028732010-03-16 16:41:46 -07001763 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001764 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001765 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001766 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1767 // the opaque region is the layer's footprint
1768 opaqueRegion = visibleRegion;
1769 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001770 }
1771 }
1772
Mathias Agopianab028732010-03-16 16:41:46 -07001773 // Clip the covered region to the visible region
1774 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1775
1776 // Update aboveCoveredLayers for next (lower) layer
1777 aboveCoveredLayers.orSelf(visibleRegion);
1778
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001779 // subtract the opaque region covered by the layers above us
1780 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001781
1782 // compute this layer's dirty region
1783 if (layer->contentDirty) {
1784 // we need to invalidate the whole region
1785 dirty = visibleRegion;
1786 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001787 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001788 layer->contentDirty = false;
1789 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001790 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001791 * the exposed region consists of two components:
1792 * 1) what's VISIBLE now and was COVERED before
1793 * 2) what's EXPOSED now less what was EXPOSED before
1794 *
1795 * note that (1) is conservative, we start with the whole
1796 * visible region but only keep what used to be covered by
1797 * something -- which mean it may have been exposed.
1798 *
1799 * (2) handles areas that were not covered by anything but got
1800 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001801 */
Mathias Agopianab028732010-03-16 16:41:46 -07001802 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001803 const Region oldVisibleRegion = layer->visibleRegion;
1804 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001805 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1806 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807 }
1808 dirty.subtractSelf(aboveOpaqueLayers);
1809
1810 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001811 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001812
Mathias Agopianab028732010-03-16 16:41:46 -07001813 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001815
Jesse Halla8026d22012-09-25 13:25:04 -07001816 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001817 layer->setVisibleRegion(visibleRegion);
1818 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001819 layer->setVisibleNonTransparentRegion(
1820 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001821 }
1822
Mathias Agopian87baae12012-07-31 12:38:26 -07001823 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001824}
1825
Mathias Agopian87baae12012-07-31 12:38:26 -07001826void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1827 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001828 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001829 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1830 if (hw->getLayerStack() == layerStack) {
1831 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001832 }
1833 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001834}
1835
Dan Stoza6b9454d2014-11-07 16:00:59 -08001836bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001837{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 ALOGV("handlePageFlip");
1839
Mathias Agopian4fec8732012-06-29 14:12:52 -07001840 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001841
Mathias Agopian4fec8732012-06-29 14:12:52 -07001842 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001843 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001844 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001845
1846 // Store the set of layers that need updates. This set must not change as
1847 // buffers are being latched, as this could result in a deadlock.
1848 // Example: Two producers share the same command stream and:
1849 // 1.) Layer 0 is latched
1850 // 2.) Layer 0 gets a new frame
1851 // 2.) Layer 1 gets a new frame
1852 // 3.) Layer 1 is latched.
1853 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1854 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001855 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001856 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001857 if (layer->hasQueuedFrame()) {
1858 frameQueued = true;
1859 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001861 } else {
1862 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001863 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001864 } else {
1865 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001866 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001867 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001869 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001870 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001871 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001872 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001873 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001874
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001875 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001876
1877 // If we will need to wake up at some time in the future to deal with a
1878 // queued frame that shouldn't be displayed during this vsync period, wake
1879 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001881 signalLayerUpdate();
1882 }
1883
1884 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001885 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886}
1887
Mathias Agopianad456f92011-01-13 17:53:01 -08001888void SurfaceFlinger::invalidateHwcGeometry()
1889{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001890 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001891}
1892
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001893
Mathias Agopiancd60f992012-08-16 16:28:27 -07001894void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001895 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001896{
Dan Stoza71433162014-02-04 16:22:36 -08001897 // We only need to actually compose the display if:
1898 // 1) It is being handled by hardware composer, which may need this to
1899 // keep its virtual display state machine in sync, or
1900 // 2) There is work to be done (the dirty region isn't empty)
1901 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1902 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001904 return;
1905 }
1906
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 ALOGV("doDisplayComposition");
1908
Mathias Agopian87baae12012-07-31 12:38:26 -07001909 Region dirtyRegion(inDirtyRegion);
1910
Mathias Agopianb8a55602009-06-26 19:06:36 -07001911 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001912 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001913
Mathias Agopian42977342012-08-05 00:40:46 -07001914 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001915 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001916 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1917 // takes a rectangle, we must make sure to update that whole
1918 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001919 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001920 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001921 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001922 // We need to redraw the rectangle that will be updated
1923 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001924 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001925 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001926 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001927 } else {
1928 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001929 dirtyRegion.set(hw->bounds());
1930 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931 }
1932 }
1933
Alan Viverette9c5a3332013-09-12 20:04:35 -07001934 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07001935 if (!doComposeSurfaces(hw, dirtyRegion)) return;
Mathias Agopianff2ed702013-09-01 21:36:12 -07001936 } else {
1937 RenderEngine& engine(getRenderEngine());
Alan Viverette9c5a3332013-09-12 20:04:35 -07001938 mat4 colorMatrix = mColorMatrix;
1939 if (mDaltonize) {
Alan Viverette9c5a3332013-09-12 20:04:35 -07001940 colorMatrix = colorMatrix * mDaltonizer();
Alan Viverette9c5a3332013-09-12 20:04:35 -07001941 }
Dan Stozaf0087992014-10-20 15:46:09 -07001942 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001943 doComposeSurfaces(hw, dirtyRegion);
Dan Stozaf0087992014-10-20 15:46:09 -07001944 engine.setupColorTransform(oldMatrix);
Mathias Agopianff2ed702013-09-01 21:36:12 -07001945 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001946
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001947 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001948 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001949
1950 // swap buffers (presentation)
1951 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001952}
1953
Dan Stoza9e56aa02015-11-02 13:00:03 -08001954bool SurfaceFlinger::doComposeSurfaces(
1955 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001956{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001957 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 const auto hwcId = displayDevice->getHwcDisplayId();
1960 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1961 if (hasClientComposition) {
1962 ALOGV("hasClientComposition");
1963
1964 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001965 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001967 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1968 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1969 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1970 }
1971 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001972 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001973
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001974 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001975 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1976 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001977 // when using overlays, we assume a fully transparent framebuffer
1978 // NOTE: we could reduce how much we need to clear, for instance
1979 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001980 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001981 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001983 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001984 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07001986
1987 // we remove the scissor part
1988 // we're left with the letterbox region
1989 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001990 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07001991
1992 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08001993 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07001994
1995 // but limit it to the dirty region
1996 region.andSelf(dirty);
1997
Mathias Agopianb9494d52012-04-18 02:28:45 -07001998 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07001999 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002000 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002001 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002002 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002003 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002004
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002006 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002007 // scissor on the main display. It should never be needed
2008 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002009 const Rect& bounds(displayDevice->getBounds());
2010 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002011 if (scissor != bounds) {
2012 // scissor doesn't match the screen's dimensions, so we
2013 // need to clear everything outside of it and enable
2014 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002015
Mathias Agopianf45c5102012-10-24 16:29:17 -07002016 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 const uint32_t height = displayDevice->getHeight();
2018 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002019 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002020 }
2021 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002022 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002023
Mathias Agopian85d751c2012-08-29 16:59:24 -07002024 /*
2025 * and then, render the layers targeted at the framebuffer
2026 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002027
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ALOGV("Rendering client layers");
2029 const Transform& displayTransform = displayDevice->getTransform();
2030 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002031 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 bool firstLayer = true;
2033 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2034 const Region clip(dirty.intersect(
2035 displayTransform.transform(layer->visibleRegion)));
2036 ALOGV("Layer: %s", layer->getName().string());
2037 ALOGV(" Composition type: %s",
2038 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002039 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 switch (layer->getCompositionType(hwcId)) {
2041 case HWC2::Composition::Cursor:
2042 case HWC2::Composition::Device:
2043 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002044 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002045 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2046 layer->isOpaque(state) && (state.alpha == 1.0f)
2047 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002048 // never clear the very first layer since we're
2049 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002050 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002051 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002052 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 case HWC2::Composition::Client: {
2055 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002056 break;
2057 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002059 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002060 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002061 } else {
2062 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002063 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002065 }
2066 } else {
2067 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002069 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002070 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002071 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002073 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002074 }
2075 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002076
2077 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002079 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002080}
2081
Mathias Agopian3f844832013-08-07 21:24:32 -07002082void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002083 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002084 RenderEngine& engine(getRenderEngine());
2085 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002086}
2087
Dan Stoza7d89d062015-04-30 13:29:25 -07002088status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002089 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002090 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002091 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002092{
Dan Stoza7d89d062015-04-30 13:29:25 -07002093 // add this layer to the current state list
2094 {
2095 Mutex::Autolock _l(mStateLock);
2096 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2097 return NO_MEMORY;
2098 }
2099 mCurrentState.layersSortedByZ.add(lbc);
2100 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2101 }
2102
Mathias Agopian96f08192010-06-02 23:28:45 -07002103 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002104 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002105
Dan Stoza7d89d062015-04-30 13:29:25 -07002106 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002107}
2108
Mathias Agopian3f844832013-08-07 21:24:32 -07002109status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002111 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002112 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002113 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002114 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002115 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002116 return NO_ERROR;
2117 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002118 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002119}
2120
Dan Stozac7014012014-02-14 15:03:43 -08002121uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002122 return android_atomic_release_load(&mTransactionFlags);
2123}
2124
Mathias Agopian3f844832013-08-07 21:24:32 -07002125uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002126 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2127}
2128
Mathias Agopian3f844832013-08-07 21:24:32 -07002129uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2131 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002132 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002133 }
2134 return old;
2135}
2136
Mathias Agopian8b33f032012-07-24 20:43:54 -07002137void SurfaceFlinger::setTransactionState(
2138 const Vector<ComposerState>& state,
2139 const Vector<DisplayState>& displays,
2140 uint32_t flags)
2141{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002142 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002143 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002144 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002145
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002146 if (flags & eAnimation) {
2147 // For window updates that are part of an animation we must wait for
2148 // previous animation "frames" to be handled.
2149 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002150 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002151 if (CC_UNLIKELY(err != NO_ERROR)) {
2152 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002153 // caller after a few seconds.
2154 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2155 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002156 mAnimTransactionPending = false;
2157 break;
2158 }
2159 }
2160 }
2161
Mathias Agopiane57f2922012-08-09 16:29:12 -07002162 size_t count = displays.size();
2163 for (size_t i=0 ; i<count ; i++) {
2164 const DisplayState& s(displays[i]);
2165 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002166 }
2167
Mathias Agopiane57f2922012-08-09 16:29:12 -07002168 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002169 for (size_t i=0 ; i<count ; i++) {
2170 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002171 // Here we need to check that the interface we're given is indeed
2172 // one of our own. A malicious client could give us a NULL
2173 // IInterface, or one of its own or even one of our own but a
2174 // different type. All these situations would cause us to crash.
2175 //
2176 // NOTE: it would be better to use RTTI as we could directly check
2177 // that we have a Client*. however, RTTI is disabled in Android.
2178 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002179 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002180 if (binder != NULL) {
2181 String16 desc(binder->getInterfaceDescriptor());
2182 if (desc == ISurfaceComposerClient::descriptor) {
2183 sp<Client> client( static_cast<Client *>(s.client.get()) );
2184 transactionFlags |= setClientStateLocked(client, s.state);
2185 }
2186 }
2187 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002188 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002189
Robert Carr2a7dbb42016-05-24 11:41:28 -07002190 // If a synchronous transaction is explicitly requested without any changes,
2191 // force a transaction anyway. This can be used as a flush mechanism for
2192 // previous async transactions.
2193 if (transactionFlags == 0 && (flags & eSynchronous)) {
2194 transactionFlags = eTransactionNeeded;
2195 }
2196
Mathias Agopian386aa982011-11-07 21:58:03 -08002197 if (transactionFlags) {
2198 // this triggers the transaction
2199 setTransactionFlags(transactionFlags);
2200
2201 // if this is a synchronous transaction, wait for it to take effect
2202 // before returning.
2203 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002204 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002205 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002206 if (flags & eAnimation) {
2207 mAnimTransactionPending = true;
2208 }
2209 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002210 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2211 if (CC_UNLIKELY(err != NO_ERROR)) {
2212 // just in case something goes wrong in SF, return to the
2213 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002214 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2215 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002216 break;
2217 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219 }
2220}
2221
Mathias Agopiane57f2922012-08-09 16:29:12 -07002222uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2223{
Jesse Hall9a143922012-10-04 16:29:19 -07002224 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2225 if (dpyIdx < 0)
2226 return 0;
2227
Mathias Agopiane57f2922012-08-09 16:29:12 -07002228 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002229 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002230 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002231 const uint32_t what = s.what;
2232 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002233 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002234 disp.surface = s.surface;
2235 flags |= eDisplayTransactionNeeded;
2236 }
2237 }
2238 if (what & DisplayState::eLayerStackChanged) {
2239 if (disp.layerStack != s.layerStack) {
2240 disp.layerStack = s.layerStack;
2241 flags |= eDisplayTransactionNeeded;
2242 }
2243 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002244 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002245 if (disp.orientation != s.orientation) {
2246 disp.orientation = s.orientation;
2247 flags |= eDisplayTransactionNeeded;
2248 }
2249 if (disp.frame != s.frame) {
2250 disp.frame = s.frame;
2251 flags |= eDisplayTransactionNeeded;
2252 }
2253 if (disp.viewport != s.viewport) {
2254 disp.viewport = s.viewport;
2255 flags |= eDisplayTransactionNeeded;
2256 }
2257 }
Michael Lentine47e45402014-07-18 15:34:25 -07002258 if (what & DisplayState::eDisplaySizeChanged) {
2259 if (disp.width != s.width) {
2260 disp.width = s.width;
2261 flags |= eDisplayTransactionNeeded;
2262 }
2263 if (disp.height != s.height) {
2264 disp.height = s.height;
2265 flags |= eDisplayTransactionNeeded;
2266 }
2267 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002268 }
2269 return flags;
2270}
2271
2272uint32_t SurfaceFlinger::setClientStateLocked(
2273 const sp<Client>& client,
2274 const layer_state_t& s)
2275{
2276 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002277 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002278 if (layer != 0) {
2279 const uint32_t what = s.what;
Robert Carr82364e32016-05-15 11:27:47 -07002280 bool positionAppliesWithResize =
2281 what & layer_state_t::ePositionAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002282 if (what & layer_state_t::ePositionChanged) {
Robert Carr82364e32016-05-15 11:27:47 -07002283 if (layer->setPosition(s.x, s.y, !positionAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002284 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002285 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002286 }
2287 if (what & layer_state_t::eLayerChanged) {
2288 // NOTE: index needs to be calculated before we update the state
2289 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002290 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002291 mCurrentState.layersSortedByZ.removeAt(idx);
2292 mCurrentState.layersSortedByZ.add(layer);
2293 // we need traversal (state changed)
2294 // AND transaction (list changed)
2295 flags |= eTransactionNeeded|eTraversalNeeded;
2296 }
2297 }
2298 if (what & layer_state_t::eSizeChanged) {
2299 if (layer->setSize(s.w, s.h)) {
2300 flags |= eTraversalNeeded;
2301 }
2302 }
2303 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002304 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002305 flags |= eTraversalNeeded;
2306 }
2307 if (what & layer_state_t::eMatrixChanged) {
2308 if (layer->setMatrix(s.matrix))
2309 flags |= eTraversalNeeded;
2310 }
2311 if (what & layer_state_t::eTransparentRegionChanged) {
2312 if (layer->setTransparentRegionHint(s.transparentRegion))
2313 flags |= eTraversalNeeded;
2314 }
Dan Stoza23116082015-06-18 14:58:39 -07002315 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002316 if (layer->setFlags(s.flags, s.mask))
2317 flags |= eTraversalNeeded;
2318 }
2319 if (what & layer_state_t::eCropChanged) {
2320 if (layer->setCrop(s.crop))
2321 flags |= eTraversalNeeded;
2322 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002323 if (what & layer_state_t::eFinalCropChanged) {
2324 if (layer->setFinalCrop(s.finalCrop))
2325 flags |= eTraversalNeeded;
2326 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002327 if (what & layer_state_t::eLayerStackChanged) {
2328 // NOTE: index needs to be calculated before we update the state
2329 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002330 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002331 mCurrentState.layersSortedByZ.removeAt(idx);
2332 mCurrentState.layersSortedByZ.add(layer);
2333 // we need traversal (state changed)
2334 // AND transaction (list changed)
2335 flags |= eTransactionNeeded|eTraversalNeeded;
2336 }
2337 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002338 if (what & layer_state_t::eDeferTransaction) {
2339 layer->deferTransactionUntil(s.handle, s.frameNumber);
2340 // We don't trigger a traversal here because if no other state is
2341 // changed, we don't want this to cause any more work
2342 }
Robert Carrc3574f72016-03-24 12:19:32 -07002343 if (what & layer_state_t::eOverrideScalingModeChanged) {
2344 layer->setOverrideScalingMode(s.overrideScalingMode);
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 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002348 }
2349 return flags;
2350}
2351
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002352status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002353 const String8& name,
2354 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002355 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2356 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002358 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002359 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002360 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002361 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002362 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002363 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002364
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002365 status_t result = NO_ERROR;
2366
2367 sp<Layer> layer;
2368
Mathias Agopian3165cc22012-08-08 19:42:09 -07002369 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2370 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002371 result = createNormalLayer(client,
2372 name, w, h, flags, format,
2373 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002375 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002376 result = createDimLayer(client,
2377 name, w, h, flags,
2378 handle, gbp, &layer);
2379 break;
2380 default:
2381 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002382 break;
2383 }
2384
Dan Stoza7d89d062015-04-30 13:29:25 -07002385 if (result != NO_ERROR) {
2386 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002388
2389 result = addClientLayer(client, *handle, *gbp, layer);
2390 if (result != NO_ERROR) {
2391 return result;
2392 }
2393
2394 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002395 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396}
2397
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002398status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2399 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2400 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401{
2402 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002403 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404 case PIXEL_FORMAT_TRANSPARENT:
2405 case PIXEL_FORMAT_TRANSLUCENT:
2406 format = PIXEL_FORMAT_RGBA_8888;
2407 break;
2408 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002409 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002410 break;
2411 }
2412
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002413 *outLayer = new Layer(this, client, name, w, h, flags);
2414 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2415 if (err == NO_ERROR) {
2416 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002417 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002419
2420 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2421 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422}
2423
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002424status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2425 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2426 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002428 *outLayer = new LayerDim(this, client, name, w, h, flags);
2429 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002430 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002431 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002432}
2433
Mathias Agopianac9fa422013-02-11 16:40:36 -08002434status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435{
Mathias Agopian67106042013-03-14 19:18:13 -07002436 // called by the window manager when it wants to remove a Layer
2437 status_t err = NO_ERROR;
2438 sp<Layer> l(client->getLayerUser(handle));
2439 if (l != NULL) {
2440 err = removeLayer(l);
2441 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2442 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002443 }
2444 return err;
2445}
2446
Mathias Agopian13127d82013-03-05 17:47:11 -08002447status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002448{
Mathias Agopian67106042013-03-14 19:18:13 -07002449 // called by ~LayerCleaner() when all references to the IBinder (handle)
2450 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002451 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002452 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002453 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002454 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002455 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002456 "error removing layer=%p (%s)", l.get(), strerror(-err));
2457 }
2458 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459}
2460
Mathias Agopianb60314a2012-04-10 22:09:54 -07002461// ---------------------------------------------------------------------------
2462
Andy McFadden13a082e2012-08-24 10:16:42 -07002463void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002464 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002465 Vector<ComposerState> state;
2466 Vector<DisplayState> displays;
2467 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002468 d.what = DisplayState::eDisplayProjectionChanged |
2469 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002470 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002471 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002472 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002473 d.frame.makeInvalid();
2474 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002475 d.width = 0;
2476 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002477 displays.add(d);
2478 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002479 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002480
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2482 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002483 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002484}
2485
2486void SurfaceFlinger::initializeDisplays() {
2487 class MessageScreenInitialized : public MessageBase {
2488 SurfaceFlinger* flinger;
2489 public:
2490 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2491 virtual bool handler() {
2492 flinger->onInitializeDisplays();
2493 return true;
2494 }
2495 };
2496 sp<MessageBase> msg = new MessageScreenInitialized(this);
2497 postMessageAsync(msg); // we may be called from main thread, use async message
2498}
2499
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002500void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2501 int mode) {
2502 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2503 this);
2504 int32_t type = hw->getDisplayType();
2505 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002506
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002507 if (mode == currentMode) {
2508 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002509 return;
2510 }
2511
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002512 hw->setPowerMode(mode);
2513 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2514 ALOGW("Trying to set power mode for virtual display");
2515 return;
2516 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002517
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002518 if (currentMode == HWC_POWER_MODE_OFF) {
2519 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002520 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2521 // FIXME: eventthread only knows about the main display right now
2522 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002523 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002526 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002527 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002528 repaintEverything();
2529 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002530 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002531 disableHardwareVsync(true); // also cancels any in-progress resync
2532
Mathias Agopiancde87a32012-09-13 14:09:01 -07002533 // FIXME: eventthread only knows about the main display right now
2534 mEventThread->onScreenReleased();
2535 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002536
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002537 getHwComposer().setPowerMode(type, mode);
2538 mVisibleRegionsDirty = true;
2539 // from this point on, SF will stop drawing on this display
2540 } else {
2541 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002542 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002543}
2544
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002545void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2546 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002547 SurfaceFlinger& mFlinger;
2548 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002549 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002550 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002551 MessageSetPowerMode(SurfaceFlinger& flinger,
2552 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2553 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002554 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002555 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002556 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002557 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002558 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002559 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002560 ALOGW("Attempt to set power mode = %d for virtual display",
2561 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002562 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002563 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002564 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002565 return true;
2566 }
2567 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002568 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002569 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002570}
2571
2572// ---------------------------------------------------------------------------
2573
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2575{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002577
Mathias Agopianbd115332013-04-18 16:41:04 -07002578 IPCThreadState* ipc = IPCThreadState::self();
2579 const int pid = ipc->getCallingPid();
2580 const int uid = ipc->getCallingUid();
2581 if ((uid != AID_SHELL) &&
2582 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002583 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002584 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002586 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002587 // (this would indicate SF is stuck, but we want to be able to
2588 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002589 status_t err = mStateLock.timedLock(s2ns(1));
2590 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002591 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002592 result.appendFormat(
2593 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2594 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002595 }
2596
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002597 bool dumpAll = true;
2598 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002599 size_t numArgs = args.size();
2600 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002601 if ((index < numArgs) &&
2602 (args[index] == String16("--list"))) {
2603 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002604 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002605 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002606 }
2607
2608 if ((index < numArgs) &&
2609 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002610 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002611 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002612 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002613 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002614
2615 if ((index < numArgs) &&
2616 (args[index] == String16("--latency-clear"))) {
2617 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002618 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002619 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002620 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002621
2622 if ((index < numArgs) &&
2623 (args[index] == String16("--dispsync"))) {
2624 index++;
2625 mPrimaryDispSync.dump(result);
2626 dumpAll = false;
2627 }
Dan Stozab90cf072015-03-05 11:05:59 -08002628
2629 if ((index < numArgs) &&
2630 (args[index] == String16("--static-screen"))) {
2631 index++;
2632 dumpStaticScreenStats(result);
2633 dumpAll = false;
2634 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002635
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002636#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002637 if ((index < numArgs) &&
2638 (args[index] == String16("--fences"))) {
2639 index++;
2640 mFenceTracker.dump(&result);
2641 dumpAll = false;
2642 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002643#endif
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002645
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002646 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002647 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002648 }
2649
Mathias Agopian9795c422009-08-26 16:36:26 -07002650 if (locked) {
2651 mStateLock.unlock();
2652 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653 }
2654 write(fd, result.string(), result.size());
2655 return NO_ERROR;
2656}
2657
Dan Stozac7014012014-02-14 15:03:43 -08002658void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2659 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002660{
2661 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2662 const size_t count = currentLayers.size();
2663 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002664 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002665 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002666 }
2667}
2668
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002669void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002670 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002671{
2672 String8 name;
2673 if (index < args.size()) {
2674 name = String8(args[index]);
2675 index++;
2676 }
2677
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2679 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002680 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002681
2682 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002683 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002684 } else {
2685 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2686 const size_t count = currentLayers.size();
2687 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002688 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002689 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002690 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002691 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002692 }
2693 }
2694}
2695
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002696void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002697 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002698{
2699 String8 name;
2700 if (index < args.size()) {
2701 name = String8(args[index]);
2702 index++;
2703 }
2704
2705 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2706 const size_t count = currentLayers.size();
2707 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002708 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002709 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002710 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002711 }
2712 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002713
Svetoslavd85084b2014-03-20 10:28:31 -07002714 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002715}
2716
Jamie Gennis6547ff42013-07-16 20:12:42 -07002717// This should only be called from the main thread. Otherwise it would need
2718// the lock and should use mCurrentState rather than mDrawingState.
2719void SurfaceFlinger::logFrameStats() {
2720 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2721 const size_t count = drawingLayers.size();
2722 for (size_t i=0 ; i<count ; i++) {
2723 const sp<Layer>& layer(drawingLayers[i]);
2724 layer->logFrameStats();
2725 }
2726
2727 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2728}
2729
Andy McFadden4803b742012-09-24 19:07:20 -07002730/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2731{
2732 static const char* config =
2733 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002734#ifdef HAS_CONTEXT_PRIORITY
2735 " HAS_CONTEXT_PRIORITY"
2736#endif
2737#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2738 " NEVER_DEFAULT_TO_ASYNC_MODE"
2739#endif
2740#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2741 " TARGET_DISABLE_TRIPLE_BUFFERING"
2742#endif
2743 "]";
2744 result.append(config);
2745}
2746
Dan Stozab90cf072015-03-05 11:05:59 -08002747void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2748{
2749 result.appendFormat("Static screen stats:\n");
2750 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2751 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2752 float percent = 100.0f *
2753 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2754 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2755 b + 1, bucketTimeSec, percent);
2756 }
2757 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2758 float percent = 100.0f *
2759 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2760 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2761 NUM_BUCKETS - 1, bucketTimeSec, percent);
2762}
2763
Mathias Agopian74d211a2013-04-22 16:55:35 +02002764void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2765 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002766{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002767 bool colorize = false;
2768 if (index < args.size()
2769 && (args[index] == String16("--color"))) {
2770 colorize = true;
2771 index++;
2772 }
2773
2774 Colorizer colorizer(colorize);
2775
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002776 // figure out if we're stuck somewhere
2777 const nsecs_t now = systemTime();
2778 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2779 const nsecs_t inTransaction(mDebugInTransaction);
2780 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2781 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2782
2783 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002784 * Dump library configuration.
2785 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002786
2787 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002788 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002789 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002790 appendSfConfigString(result);
2791 appendUiConfigString(result);
2792 appendGuiConfigString(result);
2793 result.append("\n");
2794
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002795 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002796 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002797 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002798 result.append(SyncFeatures::getInstance().toString());
2799 result.append("\n");
2800
Dan Stoza9e56aa02015-11-02 13:00:03 -08002801 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2802
Andy McFadden41d67d72014-04-25 16:58:34 -07002803 colorizer.bold(result);
2804 result.append("DispSync configuration: ");
2805 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002806 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2807 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2809 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002810 result.append("\n");
2811
Dan Stozab90cf072015-03-05 11:05:59 -08002812 // Dump static screen stats
2813 result.append("\n");
2814 dumpStaticScreenStats(result);
2815 result.append("\n");
2816
Andy McFadden4803b742012-09-24 19:07:20 -07002817 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002818 * Dump the visible layer list
2819 */
2820 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2821 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002822 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002823 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002824 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002825 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002826 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002827 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002828 }
2829
2830 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002831 * Dump Display state
2832 */
2833
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002834 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002835 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002836 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002837 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2838 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002839 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002840 }
2841
2842 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002843 * Dump SurfaceFlinger global state
2844 */
2845
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002846 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002847 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002848 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002849
Mathias Agopian888c8222012-08-04 21:10:38 -07002850 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002851 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002852
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002853 colorizer.bold(result);
2854 result.appendFormat("EGL implementation : %s\n",
2855 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2856 colorizer.reset(result);
2857 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002858 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002859
Mathias Agopian875d8e12013-06-07 15:35:48 -07002860 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002861
Mathias Agopian42977342012-08-05 00:40:46 -07002862 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002863 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2864 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002865 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002866 " last eglSwapBuffers() time: %f us\n"
2867 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002868 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002869 " refresh-rate : %f fps\n"
2870 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002871 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002872 " gpu_to_cpu_unsupported : %d\n"
2873 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002874 mLastSwapBufferTime/1000.0,
2875 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002876 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 1e9 / activeConfig->getVsyncPeriod(),
2878 activeConfig->getDpiX(),
2879 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002880 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002881
Mathias Agopian74d211a2013-04-22 16:55:35 +02002882 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002883 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002884
Mathias Agopian74d211a2013-04-22 16:55:35 +02002885 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002886 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002887
2888 /*
2889 * VSYNC state
2890 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002891 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002892
2893 /*
2894 * Dump HWComposer state
2895 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002896 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002897 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002898 colorizer.reset(result);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002899 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2900 mHasColorMatrix;
2901 result.appendFormat(" h/w composer %s\n",
2902 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002903 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002904
2905 /*
2906 * Dump gralloc state
2907 */
2908 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2909 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002910}
2911
Mathias Agopian13127d82013-03-05 17:47:11 -08002912const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002913SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002914 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002915 wp<IBinder> dpy;
2916 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2917 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2918 dpy = mDisplays.keyAt(i);
2919 break;
2920 }
2921 }
2922 if (dpy == NULL) {
2923 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2924 // Just use the primary display so we have something to return
2925 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2926 }
2927 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002928}
2929
Keun young Park63f165f2012-08-31 10:53:36 -07002930bool SurfaceFlinger::startDdmConnection()
2931{
2932 void* libddmconnection_dso =
2933 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2934 if (!libddmconnection_dso) {
2935 return false;
2936 }
2937 void (*DdmConnection_start)(const char* name);
2938 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07002939 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07002940 if (!DdmConnection_start) {
2941 dlclose(libddmconnection_dso);
2942 return false;
2943 }
2944 (*DdmConnection_start)(getServiceName());
2945 return true;
2946}
2947
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948status_t SurfaceFlinger::onTransact(
2949 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2950{
2951 switch (code) {
2952 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07002953 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07002954 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07002956 case CLEAR_ANIMATION_FRAME_STATS:
2957 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002958 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002959 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 {
2961 // codes that require permission check
2962 IPCThreadState* ipc = IPCThreadState::self();
2963 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07002964 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07002965 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07002966 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002967 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002968 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2969 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002971 break;
2972 }
2973 case CAPTURE_SCREEN:
2974 {
2975 // codes that require permission check
2976 IPCThreadState* ipc = IPCThreadState::self();
2977 const int pid = ipc->getCallingPid();
2978 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07002979 if ((uid != AID_GRAPHICS) &&
2980 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00002981 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002982 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2983 return PERMISSION_DENIED;
2984 }
2985 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 }
2987 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07002988
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2990 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07002991 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08002992 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07002993 IPCThreadState* ipc = IPCThreadState::self();
2994 const int pid = ipc->getCallingPid();
2995 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00002996 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07002997 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002998 return PERMISSION_DENIED;
2999 }
3000 int n;
3001 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003002 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003003 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004 return NO_ERROR;
3005 case 1002: // SHOW_UPDATES
3006 n = data.readInt32();
3007 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003008 invalidateHwcGeometry();
3009 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003010 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003012 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003013 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003015 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003016 setTransactionFlags(
3017 eTransactionNeeded|
3018 eDisplayTransactionNeeded|
3019 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003020 return NO_ERROR;
3021 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003022 case 1006:{ // send empty update
3023 signalRefresh();
3024 return NO_ERROR;
3025 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003026 case 1008: // toggle use of hw composer
3027 n = data.readInt32();
3028 mDebugDisableHWC = n ? 1 : 0;
3029 invalidateHwcGeometry();
3030 repaintEverything();
3031 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003032 case 1009: // toggle use of transform hint
3033 n = data.readInt32();
3034 mDebugDisableTransformHint = n ? 1 : 0;
3035 invalidateHwcGeometry();
3036 repaintEverything();
3037 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003038 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003039 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 reply->writeInt32(0);
3041 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003042 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003043 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044 return NO_ERROR;
3045 case 1013: {
3046 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003047 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3048 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003049 return NO_ERROR;
3050 }
3051 case 1014: {
3052 // daltonize
3053 n = data.readInt32();
3054 switch (n % 10) {
3055 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3056 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3057 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3058 }
3059 if (n >= 10) {
3060 mDaltonizer.setMode(Daltonizer::correction);
3061 } else {
3062 mDaltonizer.setMode(Daltonizer::simulation);
3063 }
3064 mDaltonize = n > 0;
3065 invalidateHwcGeometry();
3066 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003067 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003069 case 1015: {
3070 // apply a color matrix
3071 n = data.readInt32();
3072 mHasColorMatrix = n ? 1 : 0;
3073 if (n) {
3074 // color matrix is sent as mat3 matrix followed by vec3
3075 // offset, then packed into a mat4 where the last row is
3076 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003077 for (size_t i = 0 ; i < 4; i++) {
3078 for (size_t j = 0; j < 4; j++) {
3079 mColorMatrix[i][j] = data.readFloat();
3080 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003081 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003082 } else {
3083 mColorMatrix = mat4();
3084 }
3085 invalidateHwcGeometry();
3086 repaintEverything();
3087 return NO_ERROR;
3088 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003089 // This is an experimental interface
3090 // Needs to be shifted to proper binder interface when we productize
3091 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003092 n = data.readInt32();
3093 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003094 return NO_ERROR;
3095 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003096 case 1017: {
3097 n = data.readInt32();
3098 mForceFullDamage = static_cast<bool>(n);
3099 return NO_ERROR;
3100 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003101 case 1018: { // Modify Choreographer's phase offset
3102 n = data.readInt32();
3103 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3104 return NO_ERROR;
3105 }
3106 case 1019: { // Modify SurfaceFlinger's phase offset
3107 n = data.readInt32();
3108 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3109 return NO_ERROR;
3110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111 }
3112 }
3113 return err;
3114}
3115
Mathias Agopian53331da2011-08-22 21:44:41 -07003116void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003117 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003118 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003119}
3120
Mathias Agopian59119e62010-10-11 12:37:43 -07003121// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003122// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003123// ---------------------------------------------------------------------------
3124
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003125/* The code below is here to handle b/8734824
3126 *
3127 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003128 * from the surfaceflinger thread to the calling binder thread, where they
3129 * are executed. This allows the calling thread in the calling process to be
3130 * reused and not depend on having "enough" binder threads to handle the
3131 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003132 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003133class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003134 /* Parts of GraphicProducerWrapper are run on two different threads,
3135 * communicating by sending messages via Looper but also by shared member
3136 * data. Coherence maintenance is subtle and in places implicit (ugh).
3137 *
3138 * Don't rely on Looper's sendMessage/handleMessage providing
3139 * release/acquire semantics for any data not actually in the Message.
3140 * Data going from surfaceflinger to binder threads needs to be
3141 * synchronized explicitly.
3142 *
3143 * Barrier open/wait do provide release/acquire semantics. This provides
3144 * implicit synchronization for data coming back from binder to
3145 * surfaceflinger threads.
3146 */
3147
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003148 sp<IGraphicBufferProducer> impl;
3149 sp<Looper> looper;
3150 status_t result;
3151 bool exitPending;
3152 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003153 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003154 uint32_t code;
3155 Parcel const* data;
3156 Parcel* reply;
3157
3158 enum {
3159 MSG_API_CALL,
3160 MSG_EXIT
3161 };
3162
3163 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003164 * Called on surfaceflinger thread. This is called by our "fake"
3165 * BpGraphicBufferProducer. We package the data and reply Parcel and
3166 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003167 */
3168 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003169 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003170 this->code = code;
3171 this->data = &data;
3172 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003173 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003174 // if we've exited, we run the message synchronously right here.
3175 // note (JH): as far as I can tell from looking at the code, this
3176 // never actually happens. if it does, i'm not sure if it happens
3177 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003178 handleMessage(Message(MSG_API_CALL));
3179 } else {
3180 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003181 // Prevent stores to this->{code, data, reply} from being
3182 // reordered later than the construction of Message.
3183 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003184 looper->sendMessage(this, Message(MSG_API_CALL));
3185 barrier.wait();
3186 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003187 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003188 }
3189
3190 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003191 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003192 * call the real BpGraphicBufferProducer.
3193 */
3194 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003195 int what = message.what;
3196 // Prevent reads below from happening before the read from Message
3197 atomic_thread_fence(memory_order_acquire);
3198 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003199 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003200 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003201 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003202 exitRequested = true;
3203 }
3204 }
3205
3206public:
Jesse Hallb154c422014-07-13 12:47:02 -07003207 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3208 : impl(impl),
3209 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003210 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003211 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003212 exitRequested(false),
3213 code(0),
3214 data(NULL),
3215 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003216 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003217
Jesse Hallb154c422014-07-13 12:47:02 -07003218 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003219 status_t waitForResponse() {
3220 do {
3221 looper->pollOnce(-1);
3222 } while (!exitRequested);
3223 return result;
3224 }
3225
Jesse Hallb154c422014-07-13 12:47:02 -07003226 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003227 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003228 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003229 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003230 // Ensure this->result is visible to the binder thread before it
3231 // handles the message.
3232 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003233 looper->sendMessage(this, Message(MSG_EXIT));
3234 }
3235};
3236
3237
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003238status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3239 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003240 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003241 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003242 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003243
3244 if (CC_UNLIKELY(display == 0))
3245 return BAD_VALUE;
3246
3247 if (CC_UNLIKELY(producer == 0))
3248 return BAD_VALUE;
3249
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003250 // if we have secure windows on this display, never allow the screen capture
3251 // unless the producer interface is local (i.e.: we can take a screenshot for
3252 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003253 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003254
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003255 // Convert to surfaceflinger's internal rotation type.
3256 Transform::orientation_flags rotationFlags;
3257 switch (rotation) {
3258 case ISurfaceComposer::eRotateNone:
3259 rotationFlags = Transform::ROT_0;
3260 break;
3261 case ISurfaceComposer::eRotate90:
3262 rotationFlags = Transform::ROT_90;
3263 break;
3264 case ISurfaceComposer::eRotate180:
3265 rotationFlags = Transform::ROT_180;
3266 break;
3267 case ISurfaceComposer::eRotate270:
3268 rotationFlags = Transform::ROT_270;
3269 break;
3270 default:
3271 rotationFlags = Transform::ROT_0;
3272 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3273 break;
3274 }
3275
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003276 class MessageCaptureScreen : public MessageBase {
3277 SurfaceFlinger* flinger;
3278 sp<IBinder> display;
3279 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003280 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003281 uint32_t reqWidth, reqHeight;
3282 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003283 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003284 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003285 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003286 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003287 public:
3288 MessageCaptureScreen(SurfaceFlinger* flinger,
3289 const sp<IBinder>& display,
3290 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003291 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003292 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003293 bool useIdentityTransform,
3294 Transform::orientation_flags rotation,
3295 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003296 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003297 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003298 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003299 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003300 rotation(rotation), result(PERMISSION_DENIED),
3301 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003302 {
3303 }
3304 status_t getResult() const {
3305 return result;
3306 }
3307 virtual bool handler() {
3308 Mutex::Autolock _l(flinger->mStateLock);
3309 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003310 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003311 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003312 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003313 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003314 return true;
3315 }
3316 };
3317
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003318 // this creates a "fake" BBinder which will serve as a "fake" remote
3319 // binder to receive the marshaled calls and forward them to the
3320 // real remote (a BpGraphicBufferProducer)
3321 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3322
3323 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3324 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003325 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003326 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003327 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003328 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003329
3330 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003331 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003332 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003333 }
3334 return res;
3335}
3336
Mathias Agopian180f10d2013-04-10 22:55:41 -07003337
3338void SurfaceFlinger::renderScreenImplLocked(
3339 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003340 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003341 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003342 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003343{
3344 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003345 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003346
3347 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003348 const int32_t hw_w = hw->getWidth();
3349 const int32_t hw_h = hw->getHeight();
3350 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003351 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003352
Dan Stozac1879002014-05-22 15:59:05 -07003353 // if a default or invalid sourceCrop is passed in, set reasonable values
3354 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3355 !sourceCrop.isValid()) {
3356 sourceCrop.setLeftTop(Point(0, 0));
3357 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3358 }
3359
3360 // ensure that sourceCrop is inside screen
3361 if (sourceCrop.left < 0) {
3362 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3363 }
Dan Stozabe31f442014-06-11 11:20:54 -07003364 if (sourceCrop.right > hw_w) {
3365 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003366 }
3367 if (sourceCrop.top < 0) {
3368 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3369 }
Dan Stozabe31f442014-06-11 11:20:54 -07003370 if (sourceCrop.bottom > hw_h) {
3371 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003372 }
3373
Mathias Agopian180f10d2013-04-10 22:55:41 -07003374 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003375 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003376
3377 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003378 engine.setViewportAndProjection(
3379 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003380 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003381
3382 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003383 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003384
3385 const LayerVector& layers( mDrawingState.layersSortedByZ );
3386 const size_t count = layers.size();
3387 for (size_t i=0 ; i<count ; ++i) {
3388 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003389 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003390 if (state.layerStack == hw->getLayerStack()) {
3391 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3392 if (layer->isVisible()) {
3393 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003394 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003395 if (filtering) layer->setFiltering(false);
3396 }
3397 }
3398 }
3399 }
3400
Mathias Agopian931bda12013-08-28 18:11:46 -07003401 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003402}
3403
3404
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003405status_t SurfaceFlinger::captureScreenImplLocked(
3406 const sp<const DisplayDevice>& hw,
3407 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003408 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003409 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003410 bool useIdentityTransform, Transform::orientation_flags rotation,
3411 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003412{
3413 ATRACE_CALL();
3414
Mathias Agopian180f10d2013-04-10 22:55:41 -07003415 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003416 uint32_t hw_w = hw->getWidth();
3417 uint32_t hw_h = hw->getHeight();
3418
3419 if (rotation & Transform::ROT_90) {
3420 std::swap(hw_w, hw_h);
3421 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003422
Mathias Agopian180f10d2013-04-10 22:55:41 -07003423 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3424 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3425 reqWidth, reqHeight, hw_w, hw_h);
3426 return BAD_VALUE;
3427 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003428
Mathias Agopian180f10d2013-04-10 22:55:41 -07003429 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3430 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3431
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003432 bool secureLayerIsVisible = false;
3433 const LayerVector& layers(mDrawingState.layersSortedByZ);
3434 const size_t count = layers.size();
3435 for (size_t i = 0 ; i < count ; ++i) {
3436 const sp<Layer>& layer(layers[i]);
3437 const Layer::State& state(layer->getDrawingState());
3438 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3439 state.z <= maxLayerZ && layer->isVisible() &&
3440 layer->isSecure()) {
3441 secureLayerIsVisible = true;
3442 }
3443 }
3444
3445 if (!isLocalScreenshot && secureLayerIsVisible) {
3446 ALOGW("FB is protected: PERMISSION_DENIED");
3447 return PERMISSION_DENIED;
3448 }
3449
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003450 // create a surface (because we're a producer, and we need to
3451 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003452 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003453 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003454
Michael Lentine5a16a622015-05-21 13:48:24 -07003455 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3456 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003457 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3458 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003459
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003460 int err = 0;
3461 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003462 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003463 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3464 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003465
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003466 if (err == NO_ERROR) {
3467 ANativeWindowBuffer* buffer;
3468 /* TODO: Once we have the sync framework everywhere this can use
3469 * server-side waits on the fence that dequeueBuffer returns.
3470 */
3471 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3472 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003473 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003474 // create an EGLImage from the buffer so we can later
3475 // turn it into a texture
3476 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3477 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3478 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003479 // this binds the given EGLImage as a framebuffer for the
3480 // duration of this scope.
3481 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3482 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003483 // this will in fact render into our dequeued buffer
3484 // via an FBO, which means we didn't have to create
3485 // an EGLSurface and therefore we're not
3486 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003487 renderScreenImplLocked(
3488 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3489 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003490
Riley Andrews86639902014-08-15 12:27:24 -07003491 // Attempt to create a sync khr object that can produce a sync point. If that
3492 // isn't available, create a non-dupable sync object in the fallback path and
3493 // wait on it directly.
3494 EGLSyncKHR sync;
3495 if (!DEBUG_SCREENSHOTS) {
3496 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003497 // native fence fd will not be populated until flush() is done.
3498 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003499 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003500 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003501 }
Riley Andrews86639902014-08-15 12:27:24 -07003502 if (sync != EGL_NO_SYNC_KHR) {
3503 // get the sync fd
3504 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3505 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3506 ALOGW("captureScreen: failed to dup sync khr object");
3507 syncFd = -1;
3508 }
3509 eglDestroySyncKHR(mEGLDisplay, sync);
3510 } else {
3511 // fallback path
3512 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3513 if (sync != EGL_NO_SYNC_KHR) {
3514 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3515 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3516 EGLint eglErr = eglGetError();
3517 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3518 ALOGW("captureScreen: fence wait timed out");
3519 } else {
3520 ALOGW_IF(eglErr != EGL_SUCCESS,
3521 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3522 }
3523 eglDestroySyncKHR(mEGLDisplay, sync);
3524 } else {
3525 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3526 }
3527 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003528 if (DEBUG_SCREENSHOTS) {
3529 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3530 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3531 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3532 hw, minLayerZ, maxLayerZ);
3533 delete [] pixels;
3534 }
3535
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003536 } else {
3537 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3538 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003539 window->cancelBuffer(window, buffer, syncFd);
3540 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003541 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003542 // destroy our image
3543 eglDestroyImageKHR(mEGLDisplay, image);
3544 } else {
3545 result = BAD_VALUE;
3546 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003547 if (buffer) {
3548 // queueBuffer takes ownership of syncFd
3549 result = window->queueBuffer(window, buffer, syncFd);
3550 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003551 }
3552 } else {
3553 result = BAD_VALUE;
3554 }
3555 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3556 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003557
Mathias Agopian74c40c02010-09-29 13:02:36 -07003558 return result;
3559}
3560
Mathias Agopiand5556842013-09-19 17:08:37 -07003561void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3562 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003563 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003564 for (size_t y=0 ; y<h ; y++) {
3565 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3566 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003567 if (p[x] != 0xFF000000) return;
3568 }
3569 }
3570 ALOGE("*** we just took a black screenshot ***\n"
3571 "requested minz=%d, maxz=%d, layerStack=%d",
3572 minLayerZ, maxLayerZ, hw->getLayerStack());
3573 const LayerVector& layers( mDrawingState.layersSortedByZ );
3574 const size_t count = layers.size();
3575 for (size_t i=0 ; i<count ; ++i) {
3576 const sp<Layer>& layer(layers[i]);
3577 const Layer::State& state(layer->getDrawingState());
3578 const bool visible = (state.layerStack == hw->getLayerStack())
3579 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3580 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003581 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003582 visible ? '+' : '-',
3583 i, layer->getName().string(), state.layerStack, state.z,
3584 layer->isVisible(), state.flags, state.alpha);
3585 }
3586 }
3587}
3588
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003589// ---------------------------------------------------------------------------
3590
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003591SurfaceFlinger::LayerVector::LayerVector() {
3592}
3593
3594SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003595 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003596}
3597
3598int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3599 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003600{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003601 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003602 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3603 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003604
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003605 uint32_t ls = l->getCurrentState().layerStack;
3606 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003607 if (ls != rs)
3608 return ls - rs;
3609
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003610 uint32_t lz = l->getCurrentState().z;
3611 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003612 if (lz != rz)
3613 return lz - rz;
3614
3615 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003616}
3617
3618// ---------------------------------------------------------------------------
3619
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003620SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003621 : type(DisplayDevice::DISPLAY_ID_INVALID),
3622 layerStack(DisplayDevice::NO_LAYER_STACK),
3623 orientation(0),
3624 width(0),
3625 height(0),
3626 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003627}
3628
Pablo Ceballos53390e12015-08-04 11:25:59 -07003629SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3630 DisplayDevice::DisplayType type, bool isSecure)
3631 : type(type),
3632 layerStack(DisplayDevice::NO_LAYER_STACK),
3633 orientation(0),
3634 width(0),
3635 height(0),
3636 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003637 viewport.makeInvalid();
3638 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003639}
3640
3641// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003644
3645
3646#if defined(__gl_h_)
3647#error "don't include gl/gl.h in this file"
3648#endif
3649
3650#if defined(__gl2_h_)
3651#error "don't include gl2/gl2.h in this file"
3652#endif