blob: 683883f3d9997a714e558daf07376eca2282b1c6 [file] [log] [blame]
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001/*
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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Mark Salyzyn7823e122016-09-29 08:08:05 -070019#include <dlfcn.h>
20#include <errno.h>
21#include <inttypes.h>
22#include <math.h>
23#include <stdatomic.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000024#include <stdint.h>
25#include <sys/types.h>
Dan Stoza9e56aa02015-11-02 13:00:03 -080026
Fabien Sanglard9d96de42016-10-11 00:15:18 +000027#include <mutex>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000028
29#include <EGL/egl.h>
30
Fabien Sanglard9d96de42016-10-11 00:15:18 +000031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000033
34#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000036#include <binder/PermissionCache.h>
37
38#include <ui/DisplayInfo.h>
39#include <ui/DisplayStatInfo.h>
40
Fabien Sanglard9d96de42016-10-11 00:15:18 +000041#include <gui/BufferQueue.h>
42#include <gui/GuiConfig.h>
43#include <gui/IDisplayEventConnection.h>
44#include <gui/Surface.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000045
46#include <ui/GraphicBufferAllocator.h>
47#include <ui/HdrCapabilities.h>
48#include <ui/PixelFormat.h>
49#include <ui/UiConfig.h>
50
51#include <utils/misc.h>
52#include <utils/String8.h>
53#include <utils/String16.h>
54#include <utils/StopWatch.h>
55#include <utils/Timers.h>
56#include <utils/Trace.h>
57
58#include <private/android_filesystem_config.h>
59#include <private/gui/SyncFeatures.h>
60
61#include <set>
62
63#include "Client.h"
64#include "clz.h"
65#include "Colorizer.h"
66#include "DdmConnection.h"
67#include "DisplayDevice.h"
68#include "DispSync.h"
69#include "EventControlThread.h"
70#include "EventThread.h"
71#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000075#include "SurfaceFlinger.h"
76
77#include "DisplayHardware/FramebufferSurface.h"
78#include "DisplayHardware/HWComposer.h"
79#include "DisplayHardware/VirtualDisplaySurface.h"
80
81#include "Effects/Daltonizer.h"
82
83#include "RenderEngine/RenderEngine.h"
84#include <cutils/compiler.h>
85
86#define DISPLAY_COUNT 1
87
88/*
89 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
90 * black pixels.
91 */
92#define DEBUG_SCREENSHOTS false
93
94EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
95
Fabien Sanglard9d96de42016-10-11 00:15:18 +000096namespace android {
97
98// This is the phase offset in nanoseconds of the software vsync event
99// relative to the vsync event reported by HWComposer. The software vsync
100// event is when SurfaceFlinger and Choreographer-based applications run each
101// frame.
102//
103// This phase offset allows adjustment of the minimum latency from application
104// wake-up (by Choregographer) time to the time at which the resulting window
105// image is displayed. This value may be either positive (after the HW vsync)
106// or negative (before the HW vsync). Setting it to 0 will result in a
107// minimum latency of two vsync periods because the app and SurfaceFlinger
108// will run just after the HW vsync. Setting it to a positive number will
109// result in the minimum latency being:
110//
111// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
112//
113// Note that reducing this latency makes it more likely for the applications
114// to not have their window content image ready in time. When this happens
115// the latency will end up being an additional vsync period, and animations
116// will hiccup. Therefore, this latency should be tuned somewhat
117// conservatively (or at least with awareness of the trade-off being made).
118static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
119
120// This is the phase offset at which SurfaceFlinger's composition runs.
121static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
122
123// ---------------------------------------------------------------------------
124
125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
131
132SurfaceFlinger::SurfaceFlinger()
133 : BnSurfaceComposer(),
134 mTransactionFlags(0),
135 mTransactionPending(false),
136 mAnimTransactionPending(false),
137 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700138 mLayersAdded(false),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000139 mRepaintEverything(0),
140 mRenderEngine(NULL),
141 mBootTime(systemTime()),
142 mVisibleRegionsDirty(false),
143 mHwWorkListDirty(false),
144 mAnimCompositionPending(false),
145 mDebugRegion(0),
146 mDebugDDMS(0),
147 mDebugDisableHWC(0),
148 mDebugDisableTransformHint(0),
149 mDebugInSwapBuffers(0),
150 mLastSwapBufferTime(0),
151 mDebugInTransaction(0),
152 mLastTransactionTime(0),
153 mBootFinished(false),
154 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800155 mInterceptor(this),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000156 mPrimaryDispSync("PrimaryDispSync"),
157 mPrimaryHWVsyncEnabled(false),
158 mHWVsyncAvailable(false),
159 mDaltonize(false),
160 mHasColorMatrix(false),
161 mHasPoweredOff(false),
162 mFrameBuckets(),
163 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700164 mLastSwapTime(0),
165 mNumLayers(0)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000166{
167 ALOGI("SurfaceFlinger is starting");
168
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000169 char value[PROPERTY_VALUE_MAX];
170
171 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
172 mGpuToCpuSupported = !atoi(value);
173
174 property_get("debug.sf.showupdates", value, "0");
175 mDebugRegion = atoi(value);
176
177 property_get("debug.sf.ddms", value, "0");
178 mDebugDDMS = atoi(value);
179 if (mDebugDDMS) {
180 if (!startDdmConnection()) {
181 // start failed, and DDMS debugging not enabled
182 mDebugDDMS = 0;
183 }
184 }
185 ALOGI_IF(mDebugRegion, "showupdates enabled");
186 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
187
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800188 property_get("debug.sf.enable_hwc_vds", value, "0");
189 mUseHwcVirtualDisplays = atoi(value);
190 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800191
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800192 property_get("ro.sf.disable_triple_buffer", value, "1");
193 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800194 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000195}
196
197void SurfaceFlinger::onFirstRef()
198{
199 mEventQueue.init(this);
200}
201
202SurfaceFlinger::~SurfaceFlinger()
203{
204 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
205 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
206 eglTerminate(display);
207}
208
209void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
210{
211 // the window manager died on us. prepare its eulogy.
212
213 // restore initial conditions (default device unblank, etc)
214 initializeDisplays();
215
216 // restart the boot-animation
217 startBootAnim();
218}
219
Robert Carr1db73f62016-12-21 12:58:51 -0800220static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000221 status_t err = client->initCheck();
222 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800223 return client;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000224 }
Robert Carr1db73f62016-12-21 12:58:51 -0800225 return nullptr;
226}
227
228sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
229 return initClient(new Client(this));
230}
231
232sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
233 const sp<IGraphicBufferProducer>& gbp) {
234 if (authenticateSurfaceTexture(gbp) == false) {
235 return nullptr;
236 }
237 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
238 if (layer == nullptr) {
239 return nullptr;
240 }
241
242 return initClient(new Client(this, layer));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000243}
244
245sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
246 bool secure)
247{
248 class DisplayToken : public BBinder {
249 sp<SurfaceFlinger> flinger;
250 virtual ~DisplayToken() {
251 // no more references, this display must be terminated
252 Mutex::Autolock _l(flinger->mStateLock);
253 flinger->mCurrentState.displays.removeItem(this);
254 flinger->setTransactionFlags(eDisplayTransactionNeeded);
255 }
256 public:
257 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
258 : flinger(flinger) {
259 }
260 };
261
262 sp<BBinder> token = new DisplayToken(this);
263
264 Mutex::Autolock _l(mStateLock);
265 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
266 info.displayName = displayName;
267 mCurrentState.displays.add(token, info);
268 mInterceptor.saveDisplayCreation(info);
269 return token;
270}
271
272void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
273 Mutex::Autolock _l(mStateLock);
274
275 ssize_t idx = mCurrentState.displays.indexOfKey(display);
276 if (idx < 0) {
277 ALOGW("destroyDisplay: invalid display token");
278 return;
279 }
280
281 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
282 if (!info.isVirtualDisplay()) {
283 ALOGE("destroyDisplay called for non-virtual display");
284 return;
285 }
286 mInterceptor.saveDisplayDeletion(info.displayId);
287 mCurrentState.displays.removeItemsAt(idx);
288 setTransactionFlags(eDisplayTransactionNeeded);
289}
290
291void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
292 ALOGW_IF(mBuiltinDisplays[type],
293 "Overwriting display token for display type %d", type);
294 mBuiltinDisplays[type] = new BBinder();
295 // All non-virtual displays are currently considered secure.
296 DisplayDeviceState info(type, true);
297 mCurrentState.displays.add(mBuiltinDisplays[type], info);
298 mInterceptor.saveDisplayCreation(info);
299}
300
301sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
302 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
303 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
304 return NULL;
305 }
306 return mBuiltinDisplays[id];
307}
308
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000309void SurfaceFlinger::bootFinished()
310{
Wei Wangb254fa32017-01-31 17:43:23 -0800311 if (mStartBootAnimThread->join() != NO_ERROR) {
312 ALOGE("Join StartBootAnimThread failed!");
313 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000314 const nsecs_t now = systemTime();
315 const nsecs_t duration = now - mBootTime;
316 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
317 mBootFinished = true;
318
319 // wait patiently for the window manager death
320 const String16 name("window");
321 sp<IBinder> window(defaultServiceManager()->getService(name));
322 if (window != 0) {
323 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
324 }
325
326 // stop boot animation
327 // formerly we would just kill the process, but we now ask it to exit so it
328 // can choose where to stop the animation.
329 property_set("service.bootanim.exit", "1");
330
331 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
332 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
333 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
334}
335
336void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
337 class MessageDestroyGLTexture : public MessageBase {
338 RenderEngine& engine;
339 uint32_t texture;
340 public:
341 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
342 : engine(engine), texture(texture) {
343 }
344 virtual bool handler() {
345 engine.deleteTextures(1, &texture);
346 return true;
347 }
348 };
349 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
350}
351
352class DispSyncSource : public VSyncSource, private DispSync::Callback {
353public:
354 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
355 const char* name) :
356 mName(name),
357 mValue(0),
358 mTraceVsync(traceVsync),
359 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
360 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
361 mDispSync(dispSync),
362 mCallbackMutex(),
363 mCallback(),
364 mVsyncMutex(),
365 mPhaseOffset(phaseOffset),
366 mEnabled(false) {}
367
368 virtual ~DispSyncSource() {}
369
370 virtual void setVSyncEnabled(bool enable) {
371 Mutex::Autolock lock(mVsyncMutex);
372 if (enable) {
373 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
374 static_cast<DispSync::Callback*>(this));
375 if (err != NO_ERROR) {
376 ALOGE("error registering vsync callback: %s (%d)",
377 strerror(-err), err);
378 }
379 //ATRACE_INT(mVsyncOnLabel.string(), 1);
380 } else {
381 status_t err = mDispSync->removeEventListener(
382 static_cast<DispSync::Callback*>(this));
383 if (err != NO_ERROR) {
384 ALOGE("error unregistering vsync callback: %s (%d)",
385 strerror(-err), err);
386 }
387 //ATRACE_INT(mVsyncOnLabel.string(), 0);
388 }
389 mEnabled = enable;
390 }
391
392 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
393 Mutex::Autolock lock(mCallbackMutex);
394 mCallback = callback;
395 }
396
397 virtual void setPhaseOffset(nsecs_t phaseOffset) {
398 Mutex::Autolock lock(mVsyncMutex);
399
400 // Normalize phaseOffset to [0, period)
401 auto period = mDispSync->getPeriod();
402 phaseOffset %= period;
403 if (phaseOffset < 0) {
404 // If we're here, then phaseOffset is in (-period, 0). After this
405 // operation, it will be in (0, period)
406 phaseOffset += period;
407 }
408 mPhaseOffset = phaseOffset;
409
410 // If we're not enabled, we don't need to mess with the listeners
411 if (!mEnabled) {
412 return;
413 }
414
415 // Remove the listener with the old offset
416 status_t err = mDispSync->removeEventListener(
417 static_cast<DispSync::Callback*>(this));
418 if (err != NO_ERROR) {
419 ALOGE("error unregistering vsync callback: %s (%d)",
420 strerror(-err), err);
421 }
422
423 // Add a listener with the new offset
424 err = mDispSync->addEventListener(mName, mPhaseOffset,
425 static_cast<DispSync::Callback*>(this));
426 if (err != NO_ERROR) {
427 ALOGE("error registering vsync callback: %s (%d)",
428 strerror(-err), err);
429 }
430 }
431
432private:
433 virtual void onDispSyncEvent(nsecs_t when) {
434 sp<VSyncSource::Callback> callback;
435 {
436 Mutex::Autolock lock(mCallbackMutex);
437 callback = mCallback;
438
439 if (mTraceVsync) {
440 mValue = (mValue + 1) % 2;
441 ATRACE_INT(mVsyncEventLabel.string(), mValue);
442 }
443 }
444
445 if (callback != NULL) {
446 callback->onVSyncEvent(when);
447 }
448 }
449
450 const char* const mName;
451
452 int mValue;
453
454 const bool mTraceVsync;
455 const String8 mVsyncOnLabel;
456 const String8 mVsyncEventLabel;
457
458 DispSync* mDispSync;
459
460 Mutex mCallbackMutex; // Protects the following
461 sp<VSyncSource::Callback> mCallback;
462
463 Mutex mVsyncMutex; // Protects the following
464 nsecs_t mPhaseOffset;
465 bool mEnabled;
466};
467
468class InjectVSyncSource : public VSyncSource {
469public:
470 InjectVSyncSource() {}
471
472 virtual ~InjectVSyncSource() {}
473
474 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
475 std::lock_guard<std::mutex> lock(mCallbackMutex);
476 mCallback = callback;
477 }
478
479 virtual void onInjectSyncEvent(nsecs_t when) {
480 std::lock_guard<std::mutex> lock(mCallbackMutex);
481 mCallback->onVSyncEvent(when);
482 }
483
484 virtual void setVSyncEnabled(bool) {}
485 virtual void setPhaseOffset(nsecs_t) {}
486
487private:
488 std::mutex mCallbackMutex; // Protects the following
489 sp<VSyncSource::Callback> mCallback;
490};
491
492void SurfaceFlinger::init() {
493 ALOGI( "SurfaceFlinger's main thread ready to run. "
494 "Initializing graphics H/W...");
495
496 Mutex::Autolock _l(mStateLock);
497
498 // initialize EGL for the default display
499 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
500 eglInitialize(mEGLDisplay, NULL, NULL);
501
502 // start the EventThread
503 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
504 vsyncPhaseOffsetNs, true, "app");
505 mEventThread = new EventThread(vsyncSrc, *this, false);
506 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
507 sfVsyncPhaseOffsetNs, true, "sf");
508 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
509 mEventQueue.setEventThread(mSFEventThread);
510
511 // set SFEventThread to SCHED_FIFO to minimize jitter
512 struct sched_param param = {0};
513 param.sched_priority = 2;
514 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
515 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
516 }
517
518
519 // Initialize the H/W composer object. There may or may not be an
520 // actual hardware composer underneath.
521 mHwc = new HWComposer(this,
522 *static_cast<HWComposer::EventHandler *>(this));
523
524 // get a RenderEngine for the given display / config (can't fail)
525 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
526
527 // retrieve the EGL context that was selected/created
528 mEGLContext = mRenderEngine->getEGLContext();
529
530 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
531 "couldn't create EGLContext");
532
533 // initialize our non-virtual displays
534 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
535 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
536 // set-up the displays that are already connected
537 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
538 // All non-virtual displays are currently considered secure.
539 bool isSecure = true;
540 createBuiltinDisplayLocked(type);
541 wp<IBinder> token = mBuiltinDisplays[i];
542
543 sp<IGraphicBufferProducer> producer;
544 sp<IGraphicBufferConsumer> consumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -0800545 BufferQueue::createBufferQueue(&producer, &consumer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000546
547 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
548 consumer);
549 int32_t hwcId = allocateHwcDisplayId(type);
550 sp<DisplayDevice> hw = new DisplayDevice(this,
551 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
552 fbs, producer,
553 mRenderEngine->getEGLConfig());
554 if (i > DisplayDevice::DISPLAY_PRIMARY) {
555 // FIXME: currently we don't get blank/unblank requests
556 // for displays other than the main display, so we always
557 // assume a connected display is unblanked.
558 ALOGD("marking display %zu as acquired/unblanked", i);
559 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
560 }
561 mDisplays.add(token, hw);
562 }
563 }
564
565 // make the GLContext current so that we can create textures when creating Layers
566 // (which may happens before we render something)
567 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
568
569 mEventControlThread = new EventControlThread(this);
570 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
571
572 // set a fake vsync period if there is no HWComposer
573 if (mHwc->initCheck() != NO_ERROR) {
574 mPrimaryDispSync.setPeriod(16666667);
575 }
576
577 // initialize our drawing state
578 mDrawingState = mCurrentState;
579
580 // set initial conditions (e.g. unblank default device)
581 initializeDisplays();
582
583 mRenderEngine->primeCache();
584
Wei Wangb254fa32017-01-31 17:43:23 -0800585 mStartBootAnimThread = new StartBootAnimThread();
586 if (mStartBootAnimThread->Start() != NO_ERROR) {
587 ALOGE("Run StartBootAnimThread failed!");
588 }
589
590 ALOGV("Done initializing");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000591}
592
593int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
594 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
595 type : mHwc->allocateDisplayId();
596}
597
598void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800599 // Start boot animation service by setting a property mailbox
600 // if property setting thread is already running, Start() will be just a NOP
601 mStartBootAnimThread->Start();
602 // Wait until property was set
603 if (mStartBootAnimThread->join() != NO_ERROR) {
604 ALOGE("Join StartBootAnimThread failed!");
605 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000606}
607
608size_t SurfaceFlinger::getMaxTextureSize() const {
609 return mRenderEngine->getMaxTextureSize();
610}
611
612size_t SurfaceFlinger::getMaxViewportDims() const {
613 return mRenderEngine->getMaxViewportDims();
614}
615
616// ----------------------------------------------------------------------------
617
618bool SurfaceFlinger::authenticateSurfaceTexture(
619 const sp<IGraphicBufferProducer>& bufferProducer) const {
620 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800621 return authenticateSurfaceTextureLocked(bufferProducer);
622}
623
624bool SurfaceFlinger::authenticateSurfaceTextureLocked(
625 const sp<IGraphicBufferProducer>& bufferProducer) const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000626 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
627 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
628}
629
Brian Anderson069b3652016-07-22 10:32:47 -0700630status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700631 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700632 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700633 FrameEvent::REQUESTED_PRESENT,
634 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700635 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700636 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700637 FrameEvent::LAST_REFRESH_START,
Brian Andersonb04c6f02016-10-21 12:57:46 -0700638 FrameEvent::GPU_COMPOSITION_DONE,
Brian Anderson3890c392016-07-25 12:48:08 -0700639 FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700640 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700641 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700642 };
643 return NO_ERROR;
644}
645
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000646status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
647 Vector<DisplayInfo>* configs) {
648 if ((configs == NULL) || (display.get() == NULL)) {
649 return BAD_VALUE;
650 }
651
652 int32_t type = getDisplayType(display);
653 if (type < 0) return type;
654
655 // TODO: Not sure if display density should handled by SF any longer
656 class Density {
657 static int getDensityFromProperty(char const* propName) {
658 char property[PROPERTY_VALUE_MAX];
659 int density = 0;
660 if (property_get(propName, property, NULL) > 0) {
661 density = atoi(property);
662 }
663 return density;
664 }
665 public:
666 static int getEmuDensity() {
667 return getDensityFromProperty("qemu.sf.lcd_density"); }
668 static int getBuildDensity() {
669 return getDensityFromProperty("ro.sf.lcd_density"); }
670 };
671
672 configs->clear();
673
674 const Vector<HWComposer::DisplayConfig>& hwConfigs =
675 getHwComposer().getConfigs(type);
676 for (size_t c = 0; c < hwConfigs.size(); ++c) {
677 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
678 DisplayInfo info = DisplayInfo();
679
680 float xdpi = hwConfig.xdpi;
681 float ydpi = hwConfig.ydpi;
682
683 if (type == DisplayDevice::DISPLAY_PRIMARY) {
684 // The density of the device is provided by a build property
685 float density = Density::getBuildDensity() / 160.0f;
686 if (density == 0) {
687 // the build doesn't provide a density -- this is wrong!
688 // use xdpi instead
689 ALOGE("ro.sf.lcd_density must be defined as a build property");
690 density = xdpi / 160.0f;
691 }
692 if (Density::getEmuDensity()) {
693 // if "qemu.sf.lcd_density" is specified, it overrides everything
694 xdpi = ydpi = density = Density::getEmuDensity();
695 density /= 160.0f;
696 }
697 info.density = density;
698
699 // TODO: this needs to go away (currently needed only by webkit)
700 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
701 info.orientation = hw->getOrientation();
702 } else {
703 // TODO: where should this value come from?
704 static const int TV_DENSITY = 213;
705 info.density = TV_DENSITY / 160.0f;
706 info.orientation = 0;
707 }
708
709 info.w = hwConfig.width;
710 info.h = hwConfig.height;
711 info.xdpi = xdpi;
712 info.ydpi = ydpi;
713 info.fps = float(1e9 / hwConfig.refresh);
714 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
715
716 // This is how far in advance a buffer must be queued for
717 // presentation at a given time. If you want a buffer to appear
718 // on the screen at time N, you must submit the buffer before
719 // (N - presentationDeadline).
720 //
721 // Normally it's one full refresh period (to give SF a chance to
722 // latch the buffer), but this can be reduced by configuring a
723 // DispSync offset. Any additional delays introduced by the hardware
724 // composer or panel must be accounted for here.
725 //
726 // We add an additional 1ms to allow for processing time and
727 // differences between the ideal and actual refresh rate.
728 info.presentationDeadline =
729 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
730
731 // All non-virtual displays are currently considered secure.
732 info.secure = true;
733
734 configs->push_back(info);
735 }
736
737 return NO_ERROR;
738}
739
740status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
741 DisplayStatInfo* stats) {
742 if (stats == NULL) {
743 return BAD_VALUE;
744 }
745
746 // FIXME for now we always return stats for the primary display
747 memset(stats, 0, sizeof(*stats));
748 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
749 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
750 return NO_ERROR;
751}
752
753int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
754 sp<DisplayDevice> device(getDisplayDevice(display));
755 if (device != NULL) {
756 return device->getActiveConfig();
757 }
758 return BAD_VALUE;
759}
760
761void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
762 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
763 this);
764 int32_t type = hw->getDisplayType();
765 int currentMode = hw->getActiveConfig();
766
767 if (mode == currentMode) {
768 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
769 return;
770 }
771
772 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
773 ALOGW("Trying to set config for virtual display");
774 return;
775 }
776
777 hw->setActiveConfig(mode);
778 getHwComposer().setActiveConfig(type, mode);
779}
780
781status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
782 class MessageSetActiveConfig: public MessageBase {
783 SurfaceFlinger& mFlinger;
784 sp<IBinder> mDisplay;
785 int mMode;
786 public:
787 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
788 int mode) :
789 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
790 virtual bool handler() {
791 Vector<DisplayInfo> configs;
792 mFlinger.getDisplayConfigs(mDisplay, &configs);
793 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
794 ALOGE("Attempt to set active config = %d for display with %zu configs",
795 mMode, configs.size());
796 }
797 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
798 if (hw == NULL) {
799 ALOGE("Attempt to set active config = %d for null display %p",
800 mMode, mDisplay.get());
801 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
802 ALOGW("Attempt to set active config = %d for virtual display",
803 mMode);
804 } else {
805 mFlinger.setActiveConfigInternal(hw, mMode);
806 }
807 return true;
808 }
809 };
810 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
811 postMessageSync(msg);
812 return NO_ERROR;
813}
814
815status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
816 Vector<android_color_mode_t>* outColorModes) {
817 if (outColorModes == nullptr || display.get() == nullptr) {
818 return BAD_VALUE;
819 }
820
821 int32_t type = getDisplayType(display);
822 if (type < 0) return type;
823
824 std::set<android_color_mode_t> colorModes;
825 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
826 colorModes.insert(hwConfig.colorMode);
827 }
828
829 outColorModes->clear();
830 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
831
832 return NO_ERROR;
833}
834
835android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
836 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
837
838 int32_t type = getDisplayType(display);
839 if (type < 0) return static_cast<android_color_mode_t>(type);
840
841 return getHwComposer().getColorMode(type);
842}
843
844status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
845 android_color_mode_t colorMode) {
846 if (display.get() == nullptr || colorMode < 0) {
847 return BAD_VALUE;
848 }
849
850 int32_t type = getDisplayType(display);
851 if (type < 0) return type;
852 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
853 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
854 desiredConfig.colorMode = colorMode;
855 for (size_t c = 0; c < hwConfigs.size(); ++c) {
856 const HWComposer::DisplayConfig config = hwConfigs[c];
857 if (config == desiredConfig) {
858 return setActiveConfig(display, c);
859 }
860 }
861 return BAD_VALUE;
862}
863
864status_t SurfaceFlinger::clearAnimationFrameStats() {
865 Mutex::Autolock _l(mStateLock);
866 mAnimFrameTracker.clearStats();
867 return NO_ERROR;
868}
869
870status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
871 Mutex::Autolock _l(mStateLock);
872 mAnimFrameTracker.getStats(outStats);
873 return NO_ERROR;
874}
875
876status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
877 HdrCapabilities* outCapabilities) const {
878 // HWC1 does not provide HDR capabilities
879 *outCapabilities = HdrCapabilities();
880 return NO_ERROR;
881}
882
883status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
884 if (enable == mInjectVSyncs) {
885 return NO_ERROR;
886 }
887
888 if (enable) {
889 mInjectVSyncs = enable;
890 ALOGV("VSync Injections enabled");
891 if (mVSyncInjector.get() == nullptr) {
892 mVSyncInjector = new InjectVSyncSource();
893 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
894 }
895 mEventQueue.setEventThread(mInjectorEventThread);
896 } else {
897 mInjectVSyncs = enable;
898 ALOGV("VSync Injections disabled");
899 mEventQueue.setEventThread(mSFEventThread);
900 mVSyncInjector.clear();
901 }
902 return NO_ERROR;
903}
904
905status_t SurfaceFlinger::injectVSync(nsecs_t when) {
906 if (!mInjectVSyncs) {
907 ALOGE("VSync Injections not enabled");
908 return BAD_VALUE;
909 }
910 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
911 ALOGV("Injecting VSync inside SurfaceFlinger");
912 mVSyncInjector->onInjectSyncEvent(when);
913 }
914 return NO_ERROR;
915}
916
917// ----------------------------------------------------------------------------
918
919sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
920 return mEventThread->createEventConnection();
921}
922
923// ----------------------------------------------------------------------------
924
925void SurfaceFlinger::waitForEvent() {
926 mEventQueue.waitMessage();
927}
928
929void SurfaceFlinger::signalTransaction() {
930 mEventQueue.invalidate();
931}
932
933void SurfaceFlinger::signalLayerUpdate() {
934 mEventQueue.invalidate();
935}
936
937void SurfaceFlinger::signalRefresh() {
938 mEventQueue.refresh();
939}
940
941status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
942 nsecs_t reltime, uint32_t /* flags */) {
943 return mEventQueue.postMessage(msg, reltime);
944}
945
946status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
947 nsecs_t reltime, uint32_t /* flags */) {
948 status_t res = mEventQueue.postMessage(msg, reltime);
949 if (res == NO_ERROR) {
950 msg->wait();
951 }
952 return res;
953}
954
955void SurfaceFlinger::run() {
956 do {
957 waitForEvent();
958 } while (true);
959}
960
961void SurfaceFlinger::enableHardwareVsync() {
962 Mutex::Autolock _l(mHWVsyncLock);
963 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
964 mPrimaryDispSync.beginResync();
965 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
966 mEventControlThread->setVsyncEnabled(true);
967 mPrimaryHWVsyncEnabled = true;
968 }
969}
970
971void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
972 Mutex::Autolock _l(mHWVsyncLock);
973
974 if (makeAvailable) {
975 mHWVsyncAvailable = true;
976 } else if (!mHWVsyncAvailable) {
977 // Hardware vsync is not currently available, so abort the resync
978 // attempt for now
979 return;
980 }
981
982 const nsecs_t period =
983 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
984
985 mPrimaryDispSync.reset();
986 mPrimaryDispSync.setPeriod(period);
987
988 if (!mPrimaryHWVsyncEnabled) {
989 mPrimaryDispSync.beginResync();
990 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
991 mEventControlThread->setVsyncEnabled(true);
992 mPrimaryHWVsyncEnabled = true;
993 }
994}
995
996void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
997 Mutex::Autolock _l(mHWVsyncLock);
998 if (mPrimaryHWVsyncEnabled) {
999 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1000 mEventControlThread->setVsyncEnabled(false);
1001 mPrimaryDispSync.endResync();
1002 mPrimaryHWVsyncEnabled = false;
1003 }
1004 if (makeUnavailable) {
1005 mHWVsyncAvailable = false;
1006 }
1007}
1008
1009void SurfaceFlinger::resyncWithRateLimit() {
1010 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1011 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
1012 resyncToHardwareVsync(false);
1013 }
1014}
1015
Steven Thomas3cfac282017-02-06 12:29:30 -08001016void SurfaceFlinger::onVSyncReceived(HWComposer* /*composer*/, int type,
1017 nsecs_t timestamp) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001018 bool needsHwVsync = false;
1019
1020 { // Scope for the lock
1021 Mutex::Autolock _l(mHWVsyncLock);
1022 if (type == 0 && mPrimaryHWVsyncEnabled) {
1023 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1024 }
1025 }
1026
1027 if (needsHwVsync) {
1028 enableHardwareVsync();
1029 } else {
1030 disableHardwareVsync(false);
1031 }
1032}
1033
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001034void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1035 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1036 *compositorTiming = mCompositorTiming;
1037}
1038
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001039void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1040 if (mEventThread == NULL) {
1041 // This is a temporary workaround for b/7145521. A non-null pointer
1042 // does not mean EventThread has finished initializing, so this
1043 // is not a correct fix.
1044 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1045 return;
1046 }
1047
1048 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 Mutex::Autolock _l(mStateLock);
1050 if (connected) {
1051 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1052 } else {
1053 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1054 mBuiltinDisplays[type].clear();
1055 }
1056 setTransactionFlags(eDisplayTransactionNeeded);
1057
1058 // Defer EventThread notification until SF has updated mDisplays.
1059 }
1060}
1061
Steven Thomas3cfac282017-02-06 12:29:30 -08001062void SurfaceFlinger::onInvalidateReceived(HWComposer* /*composer*/) {
1063 repaintEverything();
1064}
1065
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001066void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1067 ATRACE_CALL();
1068 getHwComposer().eventControl(disp, event, enabled);
1069}
1070
1071void SurfaceFlinger::onMessageReceived(int32_t what) {
1072 ATRACE_CALL();
1073 switch (what) {
1074 case MessageQueue::INVALIDATE: {
1075 bool refreshNeeded = handleMessageTransaction();
1076 refreshNeeded |= handleMessageInvalidate();
1077 refreshNeeded |= mRepaintEverything;
1078 if (refreshNeeded) {
1079 // Signal a refresh if a transaction modified the window state,
1080 // a new buffer was latched, or if HWC has requested a full
1081 // repaint
1082 signalRefresh();
1083 }
1084 break;
1085 }
1086 case MessageQueue::REFRESH: {
1087 handleMessageRefresh();
1088 break;
1089 }
1090 }
1091}
1092
1093bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001094 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001095 if (transactionFlags) {
1096 handleTransaction(transactionFlags);
1097 return true;
1098 }
1099 return false;
1100}
1101
1102bool SurfaceFlinger::handleMessageInvalidate() {
1103 ATRACE_CALL();
1104 return handlePageFlip();
1105}
1106
1107void SurfaceFlinger::handleMessageRefresh() {
1108 ATRACE_CALL();
1109
1110 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1111
Brian Andersond6927fb2016-07-23 23:37:30 -07001112 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001113 rebuildLayerStacks();
1114 setUpHWComposer();
1115 doDebugFlashRegions();
1116 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001117 postComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001118}
1119
1120void SurfaceFlinger::doDebugFlashRegions()
1121{
1122 // is debugging enabled
1123 if (CC_LIKELY(!mDebugRegion))
1124 return;
1125
1126 const bool repaintEverything = mRepaintEverything;
1127 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1128 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1129 if (hw->isDisplayOn()) {
1130 // transform the dirty region into this screen's coordinate space
1131 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1132 if (!dirtyRegion.isEmpty()) {
1133 // redraw the whole screen
1134 doComposeSurfaces(hw, Region(hw->bounds()));
1135
1136 // and draw the dirty region
1137 const int32_t height = hw->getHeight();
1138 RenderEngine& engine(getRenderEngine());
1139 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1140
1141 hw->compositionComplete();
1142 hw->swapBuffers(getHwComposer());
1143 }
1144 }
1145 }
1146
1147 postFramebuffer();
1148
1149 if (mDebugRegion > 1) {
1150 usleep(mDebugRegion * 1000);
1151 }
1152
1153 HWComposer& hwc(getHwComposer());
1154 if (hwc.initCheck() == NO_ERROR) {
1155 status_t err = hwc.prepare();
1156 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1157 }
1158}
1159
Brian Andersond6927fb2016-07-23 23:37:30 -07001160void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001161{
1162 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001163 mDrawingState.traverseInZOrder([&](Layer* layer) {
1164 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001165 needExtraInvalidate = true;
1166 }
Robert Carr2047fae2016-11-28 14:09:09 -08001167 });
1168
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001169 if (needExtraInvalidate) {
1170 signalLayerUpdate();
1171 }
1172}
1173
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001174void SurfaceFlinger::updateCompositorTiming(
1175 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1176 std::shared_ptr<FenceTime>& presentFenceTime) {
1177 // Update queue of past composite+present times and determine the
1178 // most recently known composite to present latency.
1179 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1180 nsecs_t compositeToPresentLatency = -1;
1181 while (!mCompositePresentTimes.empty()) {
1182 CompositePresentTime& cpt = mCompositePresentTimes.front();
1183 // Cached values should have been updated before calling this method,
1184 // which helps avoid duplicate syscalls.
1185 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1186 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1187 break;
1188 }
1189 compositeToPresentLatency = displayTime - cpt.composite;
1190 mCompositePresentTimes.pop();
1191 }
1192
1193 // Don't let mCompositePresentTimes grow unbounded, just in case.
1194 while (mCompositePresentTimes.size() > 16) {
1195 mCompositePresentTimes.pop();
1196 }
1197
1198 // Integer division and modulo round toward 0 not -inf, so we need to
1199 // treat negative and positive offsets differently.
1200 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs >= 0) ?
1201 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1202 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1203
1204 // Snap the latency to a value that removes scheduling jitter from the
1205 // composition and present times, which often have >1ms of jitter.
1206 // Reducing jitter is important if an app attempts to extrapolate
1207 // something (such as user input) to an accurate diasplay time.
1208 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1209 // with (presentLatency % interval).
1210 nsecs_t snappedCompositeToPresentLatency = -1;
1211 if (compositeToPresentLatency >= 0) {
1212 nsecs_t bias = vsyncInterval / 2;
1213 int64_t extraVsyncs =
1214 (compositeToPresentLatency - idealLatency + bias) /
1215 vsyncInterval;
1216 nsecs_t extraLatency = extraVsyncs * vsyncInterval;
1217 snappedCompositeToPresentLatency = idealLatency + extraLatency;
1218 }
1219
1220 std::lock_guard<std::mutex> lock(mCompositeTimingLock);
1221 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1222 mCompositorTiming.interval = vsyncInterval;
1223 if (snappedCompositeToPresentLatency >= 0) {
1224 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1225 }
1226}
1227
1228void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001229{
Brian Andersond6927fb2016-07-23 23:37:30 -07001230 const HWComposer& hwc = getHwComposer();
1231 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1232
Brian Anderson3d4039d2016-09-23 16:31:30 -07001233 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1234 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1235 glCompositionDoneFenceTime =
1236 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1237 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1238 } else {
1239 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1240 }
1241 mGlCompositionDoneTimeline.updateSignalTimes();
1242
1243 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1244 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1245 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1246 mDisplayTimeline.push(retireFenceTime);
1247 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001248
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001249 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1250 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1251
1252 // We use the refreshStartTime which might be sampled a little later than
1253 // when we started doing work for this frame, but that should be okay
1254 // since updateCompositorTiming has snapping logic.
1255 updateCompositorTiming(
1256 vsyncPhase, vsyncInterval, refreshStartTime, retireFenceTime);
1257
Robert Carr2047fae2016-11-28 14:09:09 -08001258 mDrawingState.traverseInZOrder([&](Layer* layer) {
1259 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001260 presentFenceTime, retireFenceTime, mCompositorTiming);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001261 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001262 recordBufferingStats(layer->getName().string(),
1263 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001264 }
Robert Carr2047fae2016-11-28 14:09:09 -08001265 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001266
Brian Anderson3d4039d2016-09-23 16:31:30 -07001267 if (displayFence->isValid()) {
1268 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001269 enableHardwareVsync();
1270 } else {
1271 disableHardwareVsync(false);
1272 }
1273 }
1274
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001275 if (kIgnorePresentFences) {
1276 if (hw->isDisplayOn()) {
1277 enableHardwareVsync();
1278 }
1279 }
1280
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001281 if (mAnimCompositionPending) {
1282 mAnimCompositionPending = false;
1283
Brian Anderson3d4039d2016-09-23 16:31:30 -07001284 if (retireFenceTime->isValid()) {
1285 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001286 } else {
1287 // The HWC doesn't support present fences, so use the refresh
1288 // timestamp instead.
1289 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1290 mAnimFrameTracker.setActualPresentTime(presentTime);
1291 }
1292 mAnimFrameTracker.advanceFrame();
1293 }
1294
1295 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1296 return;
1297 }
1298
1299 nsecs_t currentTime = systemTime();
1300 if (mHasPoweredOff) {
1301 mHasPoweredOff = false;
1302 } else {
1303 nsecs_t period = mPrimaryDispSync.getPeriod();
1304 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1305 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1306 if (numPeriods < NUM_BUCKETS - 1) {
1307 mFrameBuckets[numPeriods] += elapsedTime;
1308 } else {
1309 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1310 }
1311 mTotalTime += elapsedTime;
1312 }
1313 mLastSwapTime = currentTime;
1314}
1315
1316void SurfaceFlinger::rebuildLayerStacks() {
1317 // rebuild the visible layer list per screen
1318 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1319 ATRACE_CALL();
1320 mVisibleRegionsDirty = false;
1321 invalidateHwcGeometry();
1322
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001323 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1324 Region opaqueRegion;
1325 Region dirtyRegion;
1326 Vector< sp<Layer> > layersSortedByZ;
1327 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1328 const Transform& tr(hw->getTransform());
1329 const Rect bounds(hw->getBounds());
1330 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001331 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1332 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001333
Robert Carr2047fae2016-11-28 14:09:09 -08001334 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001335 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001336 Region drawRegion(tr.transform(
1337 layer->visibleNonTransparentRegion));
1338 drawRegion.andSelf(bounds);
1339 if (!drawRegion.isEmpty()) {
1340 layersSortedByZ.add(layer);
1341 }
1342 }
Robert Carr2047fae2016-11-28 14:09:09 -08001343 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001344 }
1345 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1346 hw->undefinedRegion.set(bounds);
1347 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1348 hw->dirtyRegion.orSelf(dirtyRegion);
1349 }
1350 }
1351}
1352
1353void SurfaceFlinger::setUpHWComposer() {
1354 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1355 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1356 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1357 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1358
1359 // If nothing has changed (!dirty), don't recompose.
1360 // If something changed, but we don't currently have any visible layers,
1361 // and didn't when we last did a composition, then skip it this time.
1362 // The second rule does two things:
1363 // - When all layers are removed from a display, we'll emit one black
1364 // frame, then nothing more until we get new layers.
1365 // - When a display is created with a private layer stack, we won't
1366 // emit any black frames until a layer is added to the layer stack.
1367 bool mustRecompose = dirty && !(empty && wasEmpty);
1368
1369 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1370 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1371 mustRecompose ? "doing" : "skipping",
1372 dirty ? "+" : "-",
1373 empty ? "+" : "-",
1374 wasEmpty ? "+" : "-");
1375
1376 mDisplays[dpy]->beginFrame(mustRecompose);
1377
1378 if (mustRecompose) {
1379 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1380 }
1381 }
1382
1383 HWComposer& hwc(getHwComposer());
1384 if (hwc.initCheck() == NO_ERROR) {
1385 // build the h/w work list
1386 if (CC_UNLIKELY(mHwWorkListDirty)) {
1387 mHwWorkListDirty = false;
1388 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1389 sp<const DisplayDevice> hw(mDisplays[dpy]);
1390 const int32_t id = hw->getHwcDisplayId();
1391 if (id >= 0) {
1392 const Vector< sp<Layer> >& currentLayers(
1393 hw->getVisibleLayersSortedByZ());
1394 const size_t count = currentLayers.size();
1395 if (hwc.createWorkList(id, count) == NO_ERROR) {
1396 HWComposer::LayerListIterator cur = hwc.begin(id);
1397 const HWComposer::LayerListIterator end = hwc.end(id);
1398 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1399 const sp<Layer>& layer(currentLayers[i]);
1400 layer->setGeometry(hw, *cur);
1401 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1402 cur->setSkip(true);
1403 }
1404 }
1405 }
1406 }
1407 }
1408 }
1409
1410 // set the per-frame data
1411 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1412 sp<const DisplayDevice> hw(mDisplays[dpy]);
1413 const int32_t id = hw->getHwcDisplayId();
1414 if (id >= 0) {
1415 const Vector< sp<Layer> >& currentLayers(
1416 hw->getVisibleLayersSortedByZ());
1417 const size_t count = currentLayers.size();
1418 HWComposer::LayerListIterator cur = hwc.begin(id);
1419 const HWComposer::LayerListIterator end = hwc.end(id);
1420 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1421 /*
1422 * update the per-frame h/w composer data for each layer
1423 * and build the transparent region of the FB
1424 */
1425 const sp<Layer>& layer(currentLayers[i]);
1426 layer->setPerFrameData(hw, *cur);
1427 }
1428 }
1429 }
1430
1431 // If possible, attempt to use the cursor overlay on each display.
1432 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1433 sp<const DisplayDevice> hw(mDisplays[dpy]);
1434 const int32_t id = hw->getHwcDisplayId();
1435 if (id >= 0) {
1436 const Vector< sp<Layer> >& currentLayers(
1437 hw->getVisibleLayersSortedByZ());
1438 const size_t count = currentLayers.size();
1439 HWComposer::LayerListIterator cur = hwc.begin(id);
1440 const HWComposer::LayerListIterator end = hwc.end(id);
1441 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1442 const sp<Layer>& layer(currentLayers[i]);
1443 if (layer->isPotentialCursor()) {
1444 cur->setIsCursorLayerHint();
1445 break;
1446 }
1447 }
1448 }
1449 }
1450
1451 status_t err = hwc.prepare();
1452 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1453
1454 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1455 sp<const DisplayDevice> hw(mDisplays[dpy]);
1456 hw->prepareFrame(hwc);
1457 }
1458 }
1459}
1460
1461void SurfaceFlinger::doComposition() {
1462 ATRACE_CALL();
1463 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1464 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1465 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1466 if (hw->isDisplayOn()) {
1467 // transform the dirty region into this screen's coordinate space
1468 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1469
1470 // repaint the framebuffer (if needed)
1471 doDisplayComposition(hw, dirtyRegion);
1472
1473 hw->dirtyRegion.clear();
1474 hw->flip(hw->swapRegion);
1475 hw->swapRegion.clear();
1476 }
1477 // inform the h/w that we're done compositing
1478 hw->compositionComplete();
1479 }
1480 postFramebuffer();
1481}
1482
1483void SurfaceFlinger::postFramebuffer()
1484{
1485 ATRACE_CALL();
1486
1487 const nsecs_t now = systemTime();
1488 mDebugInSwapBuffers = now;
1489
1490 HWComposer& hwc(getHwComposer());
1491 if (hwc.initCheck() == NO_ERROR) {
1492 if (!hwc.supportsFramebufferTarget()) {
1493 // EGL spec says:
1494 // "surface must be bound to the calling thread's current context,
1495 // for the current rendering API."
1496 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1497 }
1498 hwc.commit();
1499 }
1500
1501 // make the default display current because the VirtualDisplayDevice code cannot
1502 // deal with dequeueBuffer() being called outside of the composition loop; however
1503 // the code below can call glFlush() which is allowed (and does in some case) call
1504 // dequeueBuffer().
1505 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1506
1507 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1508 sp<const DisplayDevice> hw(mDisplays[dpy]);
1509 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1510 hw->onSwapBuffersCompleted(hwc);
1511 const size_t count = currentLayers.size();
1512 int32_t id = hw->getHwcDisplayId();
1513 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1514 HWComposer::LayerListIterator cur = hwc.begin(id);
1515 const HWComposer::LayerListIterator end = hwc.end(id);
1516 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1517 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1518 }
1519 } else {
1520 for (size_t i = 0; i < count; i++) {
1521 currentLayers[i]->onLayerDisplayed(hw, NULL);
1522 }
1523 }
1524 }
1525
1526 mLastSwapBufferTime = systemTime() - now;
1527 mDebugInSwapBuffers = 0;
1528
1529 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1530 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1531 logFrameStats();
1532 }
1533}
1534
1535void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1536{
1537 ATRACE_CALL();
1538
1539 // here we keep a copy of the drawing state (that is the state that's
1540 // going to be overwritten by handleTransactionLocked()) outside of
1541 // mStateLock so that the side-effects of the State assignment
1542 // don't happen with mStateLock held (which can cause deadlocks).
1543 State drawingState(mDrawingState);
1544
1545 Mutex::Autolock _l(mStateLock);
1546 const nsecs_t now = systemTime();
1547 mDebugInTransaction = now;
1548
1549 // Here we're guaranteed that some transaction flags are set
1550 // so we can call handleTransactionLocked() unconditionally.
1551 // We call getTransactionFlags(), which will also clear the flags,
1552 // with mStateLock held to guarantee that mCurrentState won't change
1553 // until the transaction is committed.
1554
1555 transactionFlags = getTransactionFlags(eTransactionMask);
1556 handleTransactionLocked(transactionFlags);
1557
1558 mLastTransactionTime = systemTime() - now;
1559 mDebugInTransaction = 0;
1560 invalidateHwcGeometry();
1561 // here the transaction has been committed
1562}
1563
1564void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1565{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001566 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001567 mCurrentState.traverseInZOrder([](Layer* layer) {
1568 layer->notifyAvailableFrames();
1569 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001570
1571 /*
1572 * Traversal of the children
1573 * (perform the transaction for each of them if needed)
1574 */
1575
1576 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001577 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001578 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001579 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001580
1581 const uint32_t flags = layer->doTransaction(0);
1582 if (flags & Layer::eVisibleRegion)
1583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001584 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001585 }
1586
1587 /*
1588 * Perform display own transactions if needed
1589 */
1590
1591 if (transactionFlags & eDisplayTransactionNeeded) {
1592 // here we take advantage of Vector's copy-on-write semantics to
1593 // improve performance by skipping the transaction entirely when
1594 // know that the lists are identical
1595 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1596 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1597 if (!curr.isIdenticalTo(draw)) {
1598 mVisibleRegionsDirty = true;
1599 const size_t cc = curr.size();
1600 size_t dc = draw.size();
1601
1602 // find the displays that were removed
1603 // (ie: in drawing state but not in current state)
1604 // also handle displays that changed
1605 // (ie: displays that are in both lists)
1606 for (size_t i=0 ; i<dc ; i++) {
1607 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1608 if (j < 0) {
1609 // in drawing state but not in current state
1610 if (!draw[i].isMainDisplay()) {
1611 // Call makeCurrent() on the primary display so we can
1612 // be sure that nothing associated with this display
1613 // is current.
1614 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1615 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1616 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1617 if (hw != NULL)
1618 hw->disconnect(getHwComposer());
1619 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1620 mEventThread->onHotplugReceived(draw[i].type, false);
1621 mDisplays.removeItem(draw.keyAt(i));
1622 } else {
1623 ALOGW("trying to remove the main display");
1624 }
1625 } else {
1626 // this display is in both lists. see if something changed.
1627 const DisplayDeviceState& state(curr[j]);
1628 const wp<IBinder>& display(curr.keyAt(j));
1629 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1630 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1631 if (state_binder != draw_binder) {
1632 // changing the surface is like destroying and
1633 // recreating the DisplayDevice, so we just remove it
1634 // from the drawing state, so that it get re-added
1635 // below.
1636 sp<DisplayDevice> hw(getDisplayDevice(display));
1637 if (hw != NULL)
1638 hw->disconnect(getHwComposer());
1639 mDisplays.removeItem(display);
1640 mDrawingState.displays.removeItemsAt(i);
1641 dc--; i--;
1642 // at this point we must loop to the next item
1643 continue;
1644 }
1645
1646 const sp<DisplayDevice> disp(getDisplayDevice(display));
1647 if (disp != NULL) {
1648 if (state.layerStack != draw[i].layerStack) {
1649 disp->setLayerStack(state.layerStack);
1650 }
1651 if ((state.orientation != draw[i].orientation)
1652 || (state.viewport != draw[i].viewport)
1653 || (state.frame != draw[i].frame))
1654 {
1655 disp->setProjection(state.orientation,
1656 state.viewport, state.frame);
1657 }
1658 if (state.width != draw[i].width || state.height != draw[i].height) {
1659 disp->setDisplaySize(state.width, state.height);
1660 }
1661 }
1662 }
1663 }
1664
1665 // find displays that were added
1666 // (ie: in current state but not in drawing state)
1667 for (size_t i=0 ; i<cc ; i++) {
1668 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1669 const DisplayDeviceState& state(curr[i]);
1670
1671 sp<DisplaySurface> dispSurface;
1672 sp<IGraphicBufferProducer> producer;
1673 sp<IGraphicBufferProducer> bqProducer;
1674 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian1da94df2017-02-27 18:17:44 -08001675 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001676
1677 int32_t hwcDisplayId = -1;
1678 if (state.isVirtualDisplay()) {
1679 // Virtual displays without a surface are dormant:
1680 // they have external state (layer stack, projection,
1681 // etc.) but no internal state (i.e. a DisplayDevice).
1682 if (state.surface != NULL) {
1683
1684 int width = 0;
1685 int status = state.surface->query(
1686 NATIVE_WINDOW_WIDTH, &width);
1687 ALOGE_IF(status != NO_ERROR,
1688 "Unable to query width (%d)", status);
1689 int height = 0;
1690 status = state.surface->query(
1691 NATIVE_WINDOW_HEIGHT, &height);
1692 ALOGE_IF(status != NO_ERROR,
1693 "Unable to query height (%d)", status);
1694 if (mUseHwcVirtualDisplays &&
1695 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1696 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1697 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1698 hwcDisplayId = allocateHwcDisplayId(state.type);
1699 }
1700
1701 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1702 *mHwc, hwcDisplayId, state.surface,
1703 bqProducer, bqConsumer, state.displayName);
1704
1705 dispSurface = vds;
1706 producer = vds;
1707 }
1708 } else {
1709 ALOGE_IF(state.surface!=NULL,
1710 "adding a supported display, but rendering "
1711 "surface is provided (%p), ignoring it",
1712 state.surface.get());
1713 hwcDisplayId = allocateHwcDisplayId(state.type);
1714 // for supported (by hwc) displays we provide our
1715 // own rendering surface
1716 dispSurface = new FramebufferSurface(*mHwc, state.type,
1717 bqConsumer);
1718 producer = bqProducer;
1719 }
1720
1721 const wp<IBinder>& display(curr.keyAt(i));
1722 if (dispSurface != NULL) {
1723 sp<DisplayDevice> hw = new DisplayDevice(this,
1724 state.type, hwcDisplayId,
1725 mHwc->getFormat(hwcDisplayId), state.isSecure,
1726 display, dispSurface, producer,
1727 mRenderEngine->getEGLConfig());
1728 hw->setLayerStack(state.layerStack);
1729 hw->setProjection(state.orientation,
1730 state.viewport, state.frame);
1731 hw->setDisplayName(state.displayName);
1732 mDisplays.add(display, hw);
1733 if (state.isVirtualDisplay()) {
1734 if (hwcDisplayId >= 0) {
1735 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1736 hw->getWidth(), hw->getHeight(),
1737 hw->getFormat());
1738 }
1739 } else {
1740 mEventThread->onHotplugReceived(state.type, true);
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747
1748 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1749 // The transform hint might have changed for some layers
1750 // (either because a display has changed, or because a layer
1751 // as changed).
1752 //
1753 // Walk through all the layers in currentLayers,
1754 // and update their transform hint.
1755 //
1756 // If a layer is visible only on a single display, then that
1757 // display is used to calculate the hint, otherwise we use the
1758 // default display.
1759 //
1760 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1761 // the hint is set before we acquire a buffer from the surface texture.
1762 //
1763 // NOTE: layer transactions have taken place already, so we use their
1764 // drawing state. However, SurfaceFlinger's own transaction has not
1765 // happened yet, so we must use the current state layer list
1766 // (soon to become the drawing state list).
1767 //
1768 sp<const DisplayDevice> disp;
1769 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001770 bool first = true;
1771 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001772 // NOTE: we rely on the fact that layers are sorted by
1773 // layerStack first (so we don't have to traverse the list
1774 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001775 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001776 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001777 currentlayerStack = layerStack;
1778 // figure out if this layerstack is mirrored
1779 // (more than one display) if so, pick the default display,
1780 // if not, pick the only display it's on.
1781 disp.clear();
1782 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1783 sp<const DisplayDevice> hw(mDisplays[dpy]);
1784 if (hw->getLayerStack() == currentlayerStack) {
1785 if (disp == NULL) {
1786 disp = hw;
1787 } else {
1788 disp = NULL;
1789 break;
1790 }
1791 }
1792 }
1793 }
1794 if (disp == NULL) {
1795 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1796 // redraw after transform hint changes. See bug 8508397.
1797
1798 // could be null when this layer is using a layerStack
1799 // that is not visible on any display. Also can occur at
1800 // screen off/on times.
1801 disp = getDefaultDisplayDevice();
1802 }
1803 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001804
1805 first = false;
1806 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001807 }
1808
1809
1810 /*
1811 * Perform our own transaction if needed
1812 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001813
1814 if (mLayersAdded) {
1815 mLayersAdded = false;
1816 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001817 mVisibleRegionsDirty = true;
1818 }
1819
1820 // some layers might have been removed, so
1821 // we need to update the regions they're exposing.
1822 if (mLayersRemoved) {
1823 mLayersRemoved = false;
1824 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001825 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001826 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001827 // this layer is not visible anymore
1828 // TODO: we could traverse the tree from front to back and
1829 // compute the actual visible region
1830 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001831 Region visibleReg;
1832 visibleReg.set(layer->computeScreenBounds());
1833 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001834 }
Robert Carr2047fae2016-11-28 14:09:09 -08001835 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001836 }
1837
1838 commitTransaction();
1839
1840 updateCursorAsync();
1841}
1842
1843void SurfaceFlinger::updateCursorAsync()
1844{
1845 HWComposer& hwc(getHwComposer());
1846 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1847 sp<const DisplayDevice> hw(mDisplays[dpy]);
1848 const int32_t id = hw->getHwcDisplayId();
1849 if (id < 0) {
1850 continue;
1851 }
1852 const Vector< sp<Layer> >& currentLayers(
1853 hw->getVisibleLayersSortedByZ());
1854 const size_t count = currentLayers.size();
1855 HWComposer::LayerListIterator cur = hwc.begin(id);
1856 const HWComposer::LayerListIterator end = hwc.end(id);
1857 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1858 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1859 continue;
1860 }
1861 const sp<Layer>& layer(currentLayers[i]);
1862 Rect cursorPos = layer->getPosition(hw);
1863 hwc.setCursorPositionAsync(id, cursorPos);
1864 break;
1865 }
1866 }
1867}
1868
1869void SurfaceFlinger::commitTransaction()
1870{
1871 if (!mLayersPendingRemoval.isEmpty()) {
1872 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001873 for (const auto& l : mLayersPendingRemoval) {
1874 recordBufferingStats(l->getName().string(),
1875 l->getOccupancyHistory(true));
1876 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001877 }
1878 mLayersPendingRemoval.clear();
1879 }
1880
1881 // If this transaction is part of a window animation then the next frame
1882 // we composite should be considered an animation as well.
1883 mAnimCompositionPending = mAnimTransactionPending;
1884
1885 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001886 mDrawingState.traverseInZOrder([](Layer* layer) {
1887 layer->commitChildList();
1888 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001889 mTransactionPending = false;
1890 mAnimTransactionPending = false;
1891 mTransactionCV.broadcast();
1892}
1893
Robert Carr2047fae2016-11-28 14:09:09 -08001894void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001895 Region& outDirtyRegion, Region& outOpaqueRegion)
1896{
1897 ATRACE_CALL();
1898
1899 Region aboveOpaqueLayers;
1900 Region aboveCoveredLayers;
1901 Region dirty;
1902
1903 outDirtyRegion.clear();
1904
Robert Carr2047fae2016-11-28 14:09:09 -08001905 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001906 // start with the whole surface at its current location
1907 const Layer::State& s(layer->getDrawingState());
1908
1909 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001910 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001911 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001912
1913 /*
1914 * opaqueRegion: area of a surface that is fully opaque.
1915 */
1916 Region opaqueRegion;
1917
1918 /*
1919 * visibleRegion: area of a surface that is visible on screen
1920 * and not fully transparent. This is essentially the layer's
1921 * footprint minus the opaque regions above it.
1922 * Areas covered by a translucent surface are considered visible.
1923 */
1924 Region visibleRegion;
1925
1926 /*
1927 * coveredRegion: area of a surface that is covered by all
1928 * visible regions above it (which includes the translucent areas).
1929 */
1930 Region coveredRegion;
1931
1932 /*
1933 * transparentRegion: area of a surface that is hinted to be completely
1934 * transparent. This is only used to tell when the layer has no visible
1935 * non-transparent regions and can be removed from the layer list. It
1936 * does not affect the visibleRegion of this layer or any layers
1937 * beneath it. The hint may not be correct if apps don't respect the
1938 * SurfaceView restrictions (which, sadly, some don't).
1939 */
1940 Region transparentRegion;
1941
1942
1943 // handle hidden surfaces by setting the visible region to empty
1944 if (CC_LIKELY(layer->isVisible())) {
1945 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001946 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001947 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001948 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001949 if (!visibleRegion.isEmpty()) {
1950 // Remove the transparent area from the visible region
1951 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001952 if (tr.preserveRects()) {
1953 // transform the transparent region
1954 transparentRegion = tr.transform(s.activeTransparentRegion);
1955 } else {
1956 // transformation too complex, can't do the
1957 // transparent region optimization.
1958 transparentRegion.clear();
1959 }
1960 }
1961
1962 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001963 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001964 if (s.alpha==255 && !translucent &&
1965 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1966 // the opaque region is the layer's footprint
1967 opaqueRegion = visibleRegion;
1968 }
1969 }
1970 }
1971
1972 // Clip the covered region to the visible region
1973 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1974
1975 // Update aboveCoveredLayers for next (lower) layer
1976 aboveCoveredLayers.orSelf(visibleRegion);
1977
1978 // subtract the opaque region covered by the layers above us
1979 visibleRegion.subtractSelf(aboveOpaqueLayers);
1980
1981 // compute this layer's dirty region
1982 if (layer->contentDirty) {
1983 // we need to invalidate the whole region
1984 dirty = visibleRegion;
1985 // as well, as the old visible region
1986 dirty.orSelf(layer->visibleRegion);
1987 layer->contentDirty = false;
1988 } else {
1989 /* compute the exposed region:
1990 * the exposed region consists of two components:
1991 * 1) what's VISIBLE now and was COVERED before
1992 * 2) what's EXPOSED now less what was EXPOSED before
1993 *
1994 * note that (1) is conservative, we start with the whole
1995 * visible region but only keep what used to be covered by
1996 * something -- which mean it may have been exposed.
1997 *
1998 * (2) handles areas that were not covered by anything but got
1999 * exposed because of a resize.
2000 */
2001 const Region newExposed = visibleRegion - coveredRegion;
2002 const Region oldVisibleRegion = layer->visibleRegion;
2003 const Region oldCoveredRegion = layer->coveredRegion;
2004 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2005 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
2006 }
2007 dirty.subtractSelf(aboveOpaqueLayers);
2008
2009 // accumulate to the screen dirty region
2010 outDirtyRegion.orSelf(dirty);
2011
2012 // Update aboveOpaqueLayers for next (lower) layer
2013 aboveOpaqueLayers.orSelf(opaqueRegion);
2014
2015 // Store the visible region in screen space
2016 layer->setVisibleRegion(visibleRegion);
2017 layer->setCoveredRegion(coveredRegion);
2018 layer->setVisibleNonTransparentRegion(
2019 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002020 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002021
2022 outOpaqueRegion = aboveOpaqueLayers;
2023}
2024
2025void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2026 const Region& dirty) {
2027 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2028 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2029 if (hw->getLayerStack() == layerStack) {
2030 hw->dirtyRegion.orSelf(dirty);
2031 }
2032 }
2033}
2034
2035bool SurfaceFlinger::handlePageFlip()
2036{
Brian Andersond6927fb2016-07-23 23:37:30 -07002037 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002038 Region dirtyRegion;
2039
2040 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002041 bool frameQueued = false;
2042
2043 // Store the set of layers that need updates. This set must not change as
2044 // buffers are being latched, as this could result in a deadlock.
2045 // Example: Two producers share the same command stream and:
2046 // 1.) Layer 0 is latched
2047 // 2.) Layer 0 gets a new frame
2048 // 2.) Layer 1 gets a new frame
2049 // 3.) Layer 1 is latched.
2050 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2051 // second frame. But layer 0's second frame could be waiting on display.
2052 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08002053 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002054 if (layer->hasQueuedFrame()) {
2055 frameQueued = true;
2056 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002057 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002058 } else {
2059 layer->useEmptyDamage();
2060 }
2061 } else {
2062 layer->useEmptyDamage();
2063 }
Robert Carr2047fae2016-11-28 14:09:09 -08002064 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002065 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2066 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002067 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002068 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002069 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002070 }
2071
2072 mVisibleRegionsDirty |= visibleRegions;
2073
2074 // If we will need to wake up at some time in the future to deal with a
2075 // queued frame that shouldn't be displayed during this vsync period, wake
2076 // up during the next vsync period to check again.
2077 if (frameQueued && layersWithQueuedFrames.empty()) {
2078 signalLayerUpdate();
2079 }
2080
2081 // Only continue with the refresh if there is actually new work to do
2082 return !layersWithQueuedFrames.empty();
2083}
2084
2085void SurfaceFlinger::invalidateHwcGeometry()
2086{
2087 mHwWorkListDirty = true;
2088}
2089
2090
2091void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2092 const Region& inDirtyRegion)
2093{
2094 // We only need to actually compose the display if:
2095 // 1) It is being handled by hardware composer, which may need this to
2096 // keep its virtual display state machine in sync, or
2097 // 2) There is work to be done (the dirty region isn't empty)
2098 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2099 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2100 return;
2101 }
2102
2103 Region dirtyRegion(inDirtyRegion);
2104
2105 // compute the invalid region
2106 hw->swapRegion.orSelf(dirtyRegion);
2107
2108 uint32_t flags = hw->getFlags();
2109 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2110 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2111 // takes a rectangle, we must make sure to update that whole
2112 // rectangle in that case
2113 dirtyRegion.set(hw->swapRegion.bounds());
2114 } else {
2115 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2116 // We need to redraw the rectangle that will be updated
2117 // (pushed to the framebuffer).
2118 // This is needed because PARTIAL_UPDATES only takes one
2119 // rectangle instead of a region (see DisplayDevice::flip())
2120 dirtyRegion.set(hw->swapRegion.bounds());
2121 } else {
2122 // we need to redraw everything (the whole screen)
2123 dirtyRegion.set(hw->bounds());
2124 hw->swapRegion = dirtyRegion;
2125 }
2126 }
2127
2128 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2129 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2130 } else {
2131 RenderEngine& engine(getRenderEngine());
2132 mat4 colorMatrix = mColorMatrix;
2133 if (mDaltonize) {
2134 colorMatrix = colorMatrix * mDaltonizer();
2135 }
2136 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2137 doComposeSurfaces(hw, dirtyRegion);
2138 engine.setupColorTransform(oldMatrix);
2139 }
2140
2141 // update the swap region and clear the dirty region
2142 hw->swapRegion.orSelf(dirtyRegion);
2143
2144 // swap buffers (presentation)
2145 hw->swapBuffers(getHwComposer());
2146}
2147
2148bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2149{
2150 RenderEngine& engine(getRenderEngine());
2151 const int32_t id = hw->getHwcDisplayId();
2152 HWComposer& hwc(getHwComposer());
2153 HWComposer::LayerListIterator cur = hwc.begin(id);
2154 const HWComposer::LayerListIterator end = hwc.end(id);
2155
2156 bool hasGlesComposition = hwc.hasGlesComposition(id);
2157 if (hasGlesComposition) {
2158 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2159 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2160 hw->getDisplayName().string());
2161 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2162 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2163 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2164 }
2165 return false;
2166 }
2167
2168 // Never touch the framebuffer if we don't have any framebuffer layers
2169 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2170 if (hasHwcComposition) {
2171 // when using overlays, we assume a fully transparent framebuffer
2172 // NOTE: we could reduce how much we need to clear, for instance
2173 // remove where there are opaque FB layers. however, on some
2174 // GPUs doing a "clean slate" clear might be more efficient.
2175 // We'll revisit later if needed.
2176 engine.clearWithColor(0, 0, 0, 0);
2177 } else {
2178 // we start with the whole screen area
2179 const Region bounds(hw->getBounds());
2180
2181 // we remove the scissor part
2182 // we're left with the letterbox region
2183 // (common case is that letterbox ends-up being empty)
2184 const Region letterbox(bounds.subtract(hw->getScissor()));
2185
2186 // compute the area to clear
2187 Region region(hw->undefinedRegion.merge(letterbox));
2188
2189 // but limit it to the dirty region
2190 region.andSelf(dirty);
2191
2192 // screen is already cleared here
2193 if (!region.isEmpty()) {
2194 // can happen with SurfaceView
2195 drawWormhole(hw, region);
2196 }
2197 }
2198
2199 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2200 // just to be on the safe side, we don't set the
2201 // scissor on the main display. It should never be needed
2202 // anyways (though in theory it could since the API allows it).
2203 const Rect& bounds(hw->getBounds());
2204 const Rect& scissor(hw->getScissor());
2205 if (scissor != bounds) {
2206 // scissor doesn't match the screen's dimensions, so we
2207 // need to clear everything outside of it and enable
2208 // the GL scissor so we don't draw anything where we shouldn't
2209
2210 // enable scissor for this frame
2211 const uint32_t height = hw->getHeight();
2212 engine.setScissor(scissor.left, height - scissor.bottom,
2213 scissor.getWidth(), scissor.getHeight());
2214 }
2215 }
2216 }
2217
2218 /*
2219 * and then, render the layers targeted at the framebuffer
2220 */
2221
2222 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2223 const size_t count = layers.size();
2224 const Transform& tr = hw->getTransform();
2225 if (cur != end) {
2226 // we're using h/w composer
2227 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2228 const sp<Layer>& layer(layers[i]);
2229 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2230 if (!clip.isEmpty()) {
2231 switch (cur->getCompositionType()) {
2232 case HWC_CURSOR_OVERLAY:
2233 case HWC_OVERLAY: {
2234 const Layer::State& state(layer->getDrawingState());
2235 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2236 && i
2237 && layer->isOpaque(state) && (state.alpha == 0xFF)
2238 && hasGlesComposition) {
2239 // never clear the very first layer since we're
2240 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002241 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002242 }
2243 break;
2244 }
2245 case HWC_FRAMEBUFFER: {
2246 layer->draw(hw, clip);
2247 break;
2248 }
2249 case HWC_FRAMEBUFFER_TARGET: {
2250 // this should not happen as the iterator shouldn't
2251 // let us get there.
2252 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2253 break;
2254 }
2255 }
2256 }
2257 layer->setAcquireFence(hw, *cur);
2258 }
2259 } else {
2260 // we're not using h/w composer
2261 for (size_t i=0 ; i<count ; ++i) {
2262 const sp<Layer>& layer(layers[i]);
2263 const Region clip(dirty.intersect(
2264 tr.transform(layer->visibleRegion)));
2265 if (!clip.isEmpty()) {
2266 layer->draw(hw, clip);
2267 }
2268 }
2269 }
2270
2271 // disable scissor at the end of the frame
2272 engine.disableScissor();
2273 return true;
2274}
2275
2276void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2277 const int32_t height = hw->getHeight();
2278 RenderEngine& engine(getRenderEngine());
2279 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2280}
2281
2282status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2283 const sp<IBinder>& handle,
2284 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002285 const sp<Layer>& lbc,
2286 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002287{
2288 // add this layer to the current state list
2289 {
2290 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002292 return NO_MEMORY;
2293 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294 if (parent == nullptr) {
2295 mCurrentState.layersSortedByZ.add(lbc);
2296 } else {
2297 parent->addChild(lbc);
2298 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002299 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 mLayersAdded = true;
2301 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002302 }
2303
2304 // attach this layer to the client
2305 client->attachLayer(handle, lbc);
2306
2307 return NO_ERROR;
2308}
2309
Robert Carr9524cb32017-02-13 11:32:32 -08002310status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002311 const auto& p = layer->getParent();
2312 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2313 mCurrentState.layersSortedByZ.remove(layer);
2314
Robert Carr136e2f62017-02-08 17:54:29 -08002315 // As a matter of normal operation, the LayerCleaner will produce a second
2316 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2317 // so we will succeed in promoting it, but it's already been removed
2318 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2319 // otherwise something has gone wrong and we are leaking the layer.
2320 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002321 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2322 layer->getName().string(),
2323 (p != nullptr) ? p->getName().string() : "no-parent");
2324 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002325 } else if (index < 0) {
2326 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002327 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002328
2329 mLayersPendingRemoval.add(layer);
2330 mLayersRemoved = true;
2331 mNumLayers--;
2332 setTransactionFlags(eTransactionNeeded);
2333 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002334}
2335
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002336uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002337 return android_atomic_release_load(&mTransactionFlags);
2338}
2339
2340uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2341 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2342}
2343
2344uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2345 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2346 if ((old & flags)==0) { // wake the server up
2347 signalTransaction();
2348 }
2349 return old;
2350}
2351
2352void SurfaceFlinger::setTransactionState(
2353 const Vector<ComposerState>& state,
2354 const Vector<DisplayState>& displays,
2355 uint32_t flags)
2356{
2357 ATRACE_CALL();
2358 Mutex::Autolock _l(mStateLock);
2359 uint32_t transactionFlags = 0;
2360
2361 if (flags & eAnimation) {
2362 // For window updates that are part of an animation we must wait for
2363 // previous animation "frames" to be handled.
2364 while (mAnimTransactionPending) {
2365 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2366 if (CC_UNLIKELY(err != NO_ERROR)) {
2367 // just in case something goes wrong in SF, return to the
2368 // caller after a few seconds.
2369 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2370 "waiting for previous animation frame");
2371 mAnimTransactionPending = false;
2372 break;
2373 }
2374 }
2375 }
2376
2377 size_t count = displays.size();
2378 for (size_t i=0 ; i<count ; i++) {
2379 const DisplayState& s(displays[i]);
2380 transactionFlags |= setDisplayStateLocked(s);
2381 }
2382
2383 count = state.size();
2384 for (size_t i=0 ; i<count ; i++) {
2385 const ComposerState& s(state[i]);
2386 // Here we need to check that the interface we're given is indeed
2387 // one of our own. A malicious client could give us a NULL
2388 // IInterface, or one of its own or even one of our own but a
2389 // different type. All these situations would cause us to crash.
2390 //
2391 // NOTE: it would be better to use RTTI as we could directly check
2392 // that we have a Client*. however, RTTI is disabled in Android.
2393 if (s.client != NULL) {
2394 sp<IBinder> binder = IInterface::asBinder(s.client);
2395 if (binder != NULL) {
Fabien Sanglard45b20252017-01-18 16:43:18 -08002396 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002397 sp<Client> client( static_cast<Client *>(s.client.get()) );
2398 transactionFlags |= setClientStateLocked(client, s.state);
2399 }
2400 }
2401 }
2402 }
2403
2404 // If a synchronous transaction is explicitly requested without any changes,
2405 // force a transaction anyway. This can be used as a flush mechanism for
2406 // previous async transactions.
2407 if (transactionFlags == 0 && (flags & eSynchronous)) {
2408 transactionFlags = eTransactionNeeded;
2409 }
2410
2411 if (transactionFlags) {
2412 if (mInterceptor.isEnabled()) {
2413 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2414 }
2415
2416 // this triggers the transaction
2417 setTransactionFlags(transactionFlags);
2418
2419 // if this is a synchronous transaction, wait for it to take effect
2420 // before returning.
2421 if (flags & eSynchronous) {
2422 mTransactionPending = true;
2423 }
2424 if (flags & eAnimation) {
2425 mAnimTransactionPending = true;
2426 }
2427 while (mTransactionPending) {
2428 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2429 if (CC_UNLIKELY(err != NO_ERROR)) {
2430 // just in case something goes wrong in SF, return to the
2431 // called after a few seconds.
2432 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2433 mTransactionPending = false;
2434 break;
2435 }
2436 }
2437 }
2438}
2439
2440uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2441{
2442 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2443 if (dpyIdx < 0)
2444 return 0;
2445
2446 uint32_t flags = 0;
2447 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2448 if (disp.isValid()) {
2449 const uint32_t what = s.what;
2450 if (what & DisplayState::eSurfaceChanged) {
2451 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2452 disp.surface = s.surface;
2453 flags |= eDisplayTransactionNeeded;
2454 }
2455 }
2456 if (what & DisplayState::eLayerStackChanged) {
2457 if (disp.layerStack != s.layerStack) {
2458 disp.layerStack = s.layerStack;
2459 flags |= eDisplayTransactionNeeded;
2460 }
2461 }
2462 if (what & DisplayState::eDisplayProjectionChanged) {
2463 if (disp.orientation != s.orientation) {
2464 disp.orientation = s.orientation;
2465 flags |= eDisplayTransactionNeeded;
2466 }
2467 if (disp.frame != s.frame) {
2468 disp.frame = s.frame;
2469 flags |= eDisplayTransactionNeeded;
2470 }
2471 if (disp.viewport != s.viewport) {
2472 disp.viewport = s.viewport;
2473 flags |= eDisplayTransactionNeeded;
2474 }
2475 }
2476 if (what & DisplayState::eDisplaySizeChanged) {
2477 if (disp.width != s.width) {
2478 disp.width = s.width;
2479 flags |= eDisplayTransactionNeeded;
2480 }
2481 if (disp.height != s.height) {
2482 disp.height = s.height;
2483 flags |= eDisplayTransactionNeeded;
2484 }
2485 }
2486 }
2487 return flags;
2488}
2489
2490uint32_t SurfaceFlinger::setClientStateLocked(
2491 const sp<Client>& client,
2492 const layer_state_t& s)
2493{
2494 uint32_t flags = 0;
2495 sp<Layer> layer(client->getLayerUser(s.surface));
2496 if (layer != 0) {
2497 const uint32_t what = s.what;
2498 bool geometryAppliesWithResize =
2499 what & layer_state_t::eGeometryAppliesWithResize;
2500 if (what & layer_state_t::ePositionChanged) {
2501 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2502 flags |= eTraversalNeeded;
2503 }
2504 }
2505 if (what & layer_state_t::eLayerChanged) {
2506 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002507 const auto& p = layer->getParent();
2508 if (p == nullptr) {
2509 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2510 if (layer->setLayer(s.z) && idx >= 0) {
2511 mCurrentState.layersSortedByZ.removeAt(idx);
2512 mCurrentState.layersSortedByZ.add(layer);
2513 // we need traversal (state changed)
2514 // AND transaction (list changed)
2515 flags |= eTransactionNeeded|eTraversalNeeded;
2516 }
2517 } else {
2518 if (p->setChildLayer(layer, s.z)) {
2519 flags |= eTransactionNeeded|eTraversalNeeded;
2520 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002521 }
2522 }
2523 if (what & layer_state_t::eSizeChanged) {
2524 if (layer->setSize(s.w, s.h)) {
2525 flags |= eTraversalNeeded;
2526 }
2527 }
2528 if (what & layer_state_t::eAlphaChanged) {
2529 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2530 flags |= eTraversalNeeded;
2531 }
2532 if (what & layer_state_t::eMatrixChanged) {
2533 if (layer->setMatrix(s.matrix))
2534 flags |= eTraversalNeeded;
2535 }
2536 if (what & layer_state_t::eTransparentRegionChanged) {
2537 if (layer->setTransparentRegionHint(s.transparentRegion))
2538 flags |= eTraversalNeeded;
2539 }
2540 if (what & layer_state_t::eFlagsChanged) {
2541 if (layer->setFlags(s.flags, s.mask))
2542 flags |= eTraversalNeeded;
2543 }
2544 if (what & layer_state_t::eCropChanged) {
2545 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2546 flags |= eTraversalNeeded;
2547 }
2548 if (what & layer_state_t::eFinalCropChanged) {
2549 if (layer->setFinalCrop(s.finalCrop))
2550 flags |= eTraversalNeeded;
2551 }
2552 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002553 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 // We only allow setting layer stacks for top level layers,
2555 // everything else inherits layer stack from its parent.
2556 if (layer->hasParent()) {
2557 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2558 layer->getName().string());
2559 } else if (idx < 0) {
2560 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2561 "that also does not appear in the top level layer list. Something"
2562 " has gone wrong.", layer->getName().string());
2563 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002564 mCurrentState.layersSortedByZ.removeAt(idx);
2565 mCurrentState.layersSortedByZ.add(layer);
2566 // we need traversal (state changed)
2567 // AND transaction (list changed)
2568 flags |= eTransactionNeeded|eTraversalNeeded;
2569 }
2570 }
2571 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002572 if (s.barrierHandle != nullptr) {
2573 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2574 } else if (s.barrierGbp != nullptr) {
2575 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2576 if (authenticateSurfaceTextureLocked(gbp)) {
2577 const auto& otherLayer =
2578 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2579 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2580 } else {
2581 ALOGE("Attempt to defer transaction to to an"
2582 " unrecognized GraphicBufferProducer");
2583 }
2584 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002585 // We don't trigger a traversal here because if no other state is
2586 // changed, we don't want this to cause any more work
2587 }
Robert Carr1db73f62016-12-21 12:58:51 -08002588 if (what & layer_state_t::eReparentChildren) {
2589 if (layer->reparentChildren(s.reparentHandle)) {
2590 flags |= eTransactionNeeded|eTraversalNeeded;
2591 }
2592 }
Robert Carr9524cb32017-02-13 11:32:32 -08002593 if (what & layer_state_t::eDetachChildren) {
2594 layer->detachChildren();
2595 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002596 if (what & layer_state_t::eOverrideScalingModeChanged) {
2597 layer->setOverrideScalingMode(s.overrideScalingMode);
2598 // We don't trigger a traversal here because if no other state is
2599 // changed, we don't want this to cause any more work
2600 }
2601 }
2602 return flags;
2603}
2604
2605status_t SurfaceFlinger::createLayer(
2606 const String8& name,
2607 const sp<Client>& client,
2608 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002609 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2610 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002611{
2612 if (int32_t(w|h) < 0) {
2613 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2614 int(w), int(h));
2615 return BAD_VALUE;
2616 }
2617
2618 status_t result = NO_ERROR;
2619
2620 sp<Layer> layer;
2621
2622 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2623 case ISurfaceComposerClient::eFXSurfaceNormal:
2624 result = createNormalLayer(client,
2625 name, w, h, flags, format,
2626 handle, gbp, &layer);
2627 break;
2628 case ISurfaceComposerClient::eFXSurfaceDim:
2629 result = createDimLayer(client,
2630 name, w, h, flags,
2631 handle, gbp, &layer);
2632 break;
2633 default:
2634 result = BAD_VALUE;
2635 break;
2636 }
2637
2638 if (result != NO_ERROR) {
2639 return result;
2640 }
2641
Albert Chaulk479c60c2017-01-27 14:21:34 -05002642 layer->setInfo(windowType, ownerUid);
2643
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002645 if (result != NO_ERROR) {
2646 return result;
2647 }
2648 mInterceptor.saveSurfaceCreation(layer);
2649
2650 setTransactionFlags(eTransactionNeeded);
2651 return result;
2652}
2653
2654status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2655 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2656 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2657{
2658 // initialize the surfaces
2659 switch (format) {
2660 case PIXEL_FORMAT_TRANSPARENT:
2661 case PIXEL_FORMAT_TRANSLUCENT:
2662 format = PIXEL_FORMAT_RGBA_8888;
2663 break;
2664 case PIXEL_FORMAT_OPAQUE:
2665 format = PIXEL_FORMAT_RGBX_8888;
2666 break;
2667 }
2668
2669 *outLayer = new Layer(this, client, name, w, h, flags);
2670 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2671 if (err == NO_ERROR) {
2672 *handle = (*outLayer)->getHandle();
2673 *gbp = (*outLayer)->getProducer();
2674 }
2675
2676 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2677 return err;
2678}
2679
2680status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2681 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2682 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2683{
2684 *outLayer = new LayerDim(this, client, name, w, h, flags);
2685 *handle = (*outLayer)->getHandle();
2686 *gbp = (*outLayer)->getProducer();
2687 return NO_ERROR;
2688}
2689
2690status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2691{
Robert Carr9524cb32017-02-13 11:32:32 -08002692 // called by a client when it wants to remove a Layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002693 status_t err = NO_ERROR;
2694 sp<Layer> l(client->getLayerUser(handle));
2695 if (l != NULL) {
2696 mInterceptor.saveSurfaceDeletion(l);
2697 err = removeLayer(l);
2698 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2699 "error removing layer=%p (%s)", l.get(), strerror(-err));
2700 }
2701 return err;
2702}
2703
2704status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2705{
2706 // called by ~LayerCleaner() when all references to the IBinder (handle)
2707 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08002708 sp<Layer> l = layer.promote();
2709 if (l == nullptr) {
2710 // The layer has already been removed, carry on
2711 return NO_ERROR;
2712 } if (l->getParent() != nullptr) {
2713 // If we have a parent, then we can continue to live as long as it does.
2714 return NO_ERROR;
2715 }
2716 return removeLayer(l);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002717}
2718
2719// ---------------------------------------------------------------------------
2720
2721void SurfaceFlinger::onInitializeDisplays() {
2722 // reset screen orientation and use primary layer stack
2723 Vector<ComposerState> state;
2724 Vector<DisplayState> displays;
2725 DisplayState d;
2726 d.what = DisplayState::eDisplayProjectionChanged |
2727 DisplayState::eLayerStackChanged;
2728 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2729 d.layerStack = 0;
2730 d.orientation = DisplayState::eOrientationDefault;
2731 d.frame.makeInvalid();
2732 d.viewport.makeInvalid();
2733 d.width = 0;
2734 d.height = 0;
2735 displays.add(d);
2736 setTransactionState(state, displays, 0);
2737 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2738
2739 const nsecs_t period =
2740 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2741 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2742}
2743
2744void SurfaceFlinger::initializeDisplays() {
2745 class MessageScreenInitialized : public MessageBase {
2746 SurfaceFlinger* flinger;
2747 public:
2748 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2749 virtual bool handler() {
2750 flinger->onInitializeDisplays();
2751 return true;
2752 }
2753 };
2754 sp<MessageBase> msg = new MessageScreenInitialized(this);
2755 postMessageAsync(msg); // we may be called from main thread, use async message
2756}
2757
2758void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2759 int mode) {
2760 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2761 this);
2762 int32_t type = hw->getDisplayType();
2763 int currentMode = hw->getPowerMode();
2764
2765 if (mode == currentMode) {
2766 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2767 return;
2768 }
2769
2770 hw->setPowerMode(mode);
2771 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2772 ALOGW("Trying to set power mode for virtual display");
2773 return;
2774 }
2775
2776 if (mInterceptor.isEnabled()) {
2777 Mutex::Autolock _l(mStateLock);
2778 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2779 if (idx < 0) {
2780 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2781 return;
2782 }
2783 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2784 }
2785
2786 if (currentMode == HWC_POWER_MODE_OFF) {
2787 // Turn on the display
2788 getHwComposer().setPowerMode(type, mode);
2789 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2790 // FIXME: eventthread only knows about the main display right now
2791 mEventThread->onScreenAcquired();
2792 resyncToHardwareVsync(true);
2793 }
2794
2795 mVisibleRegionsDirty = true;
2796 mHasPoweredOff = true;
2797 repaintEverything();
2798
2799 struct sched_param param = {0};
2800 param.sched_priority = 1;
2801 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2802 ALOGW("Couldn't set SCHED_FIFO on display on");
2803 }
2804 } else if (mode == HWC_POWER_MODE_OFF) {
2805 // Turn off the display
2806 struct sched_param param = {0};
2807 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2808 ALOGW("Couldn't set SCHED_OTHER on display off");
2809 }
2810
2811 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2812 disableHardwareVsync(true); // also cancels any in-progress resync
2813
2814 // FIXME: eventthread only knows about the main display right now
2815 mEventThread->onScreenReleased();
2816 }
2817
2818 getHwComposer().setPowerMode(type, mode);
2819 mVisibleRegionsDirty = true;
2820 // from this point on, SF will stop drawing on this display
2821 } else {
2822 getHwComposer().setPowerMode(type, mode);
2823 }
2824}
2825
2826void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2827 class MessageSetPowerMode: public MessageBase {
2828 SurfaceFlinger& mFlinger;
2829 sp<IBinder> mDisplay;
2830 int mMode;
2831 public:
2832 MessageSetPowerMode(SurfaceFlinger& flinger,
2833 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2834 mDisplay(disp) { mMode = mode; }
2835 virtual bool handler() {
2836 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2837 if (hw == NULL) {
2838 ALOGE("Attempt to set power mode = %d for null display %p",
2839 mMode, mDisplay.get());
2840 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2841 ALOGW("Attempt to set power mode = %d for virtual display",
2842 mMode);
2843 } else {
2844 mFlinger.setPowerModeInternal(hw, mMode);
2845 }
2846 return true;
2847 }
2848 };
2849 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2850 postMessageSync(msg);
2851}
2852
2853// ---------------------------------------------------------------------------
2854
2855status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2856{
2857 String8 result;
2858
2859 IPCThreadState* ipc = IPCThreadState::self();
2860 const int pid = ipc->getCallingPid();
2861 const int uid = ipc->getCallingUid();
2862 if ((uid != AID_SHELL) &&
2863 !PermissionCache::checkPermission(sDump, pid, uid)) {
2864 result.appendFormat("Permission Denial: "
2865 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2866 } else {
2867 // Try to get the main lock, but give up after one second
2868 // (this would indicate SF is stuck, but we want to be able to
2869 // print something in dumpsys).
2870 status_t err = mStateLock.timedLock(s2ns(1));
2871 bool locked = (err == NO_ERROR);
2872 if (!locked) {
2873 result.appendFormat(
2874 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2875 "dumping anyways (no locks held)\n", strerror(-err), err);
2876 }
2877
2878 bool dumpAll = true;
2879 size_t index = 0;
2880 size_t numArgs = args.size();
2881 if (numArgs) {
2882 if ((index < numArgs) &&
2883 (args[index] == String16("--list"))) {
2884 index++;
2885 listLayersLocked(args, index, result);
2886 dumpAll = false;
2887 }
2888
2889 if ((index < numArgs) &&
2890 (args[index] == String16("--latency"))) {
2891 index++;
2892 dumpStatsLocked(args, index, result);
2893 dumpAll = false;
2894 }
2895
2896 if ((index < numArgs) &&
2897 (args[index] == String16("--latency-clear"))) {
2898 index++;
2899 clearStatsLocked(args, index, result);
2900 dumpAll = false;
2901 }
2902
2903 if ((index < numArgs) &&
2904 (args[index] == String16("--dispsync"))) {
2905 index++;
2906 mPrimaryDispSync.dump(result);
2907 dumpAll = false;
2908 }
2909
2910 if ((index < numArgs) &&
2911 (args[index] == String16("--static-screen"))) {
2912 index++;
2913 dumpStaticScreenStats(result);
2914 dumpAll = false;
2915 }
2916
2917 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002918 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002919 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002920 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002921 dumpAll = false;
2922 }
2923 }
2924
2925 if (dumpAll) {
2926 dumpAllLocked(args, index, result);
2927 }
2928
2929 if (locked) {
2930 mStateLock.unlock();
2931 }
2932 }
2933 write(fd, result.string(), result.size());
2934 return NO_ERROR;
2935}
2936
2937void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2938 size_t& /* index */, String8& result) const
2939{
Robert Carr2047fae2016-11-28 14:09:09 -08002940 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002941 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002942 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002943}
2944
2945void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2946 String8& result) const
2947{
2948 String8 name;
2949 if (index < args.size()) {
2950 name = String8(args[index]);
2951 index++;
2952 }
2953
2954 const nsecs_t period =
2955 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2956 result.appendFormat("%" PRId64 "\n", period);
2957
2958 if (name.isEmpty()) {
2959 mAnimFrameTracker.dumpStats(result);
2960 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002961 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002962 if (name == layer->getName()) {
2963 layer->dumpFrameStats(result);
2964 }
Robert Carr2047fae2016-11-28 14:09:09 -08002965 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002966 }
2967}
2968
2969void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2970 String8& /* result */)
2971{
2972 String8 name;
2973 if (index < args.size()) {
2974 name = String8(args[index]);
2975 index++;
2976 }
2977
Robert Carr2047fae2016-11-28 14:09:09 -08002978 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002979 if (name.isEmpty() || (name == layer->getName())) {
2980 layer->clearFrameStats();
2981 }
Robert Carr2047fae2016-11-28 14:09:09 -08002982 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002983
2984 mAnimFrameTracker.clearStats();
2985}
2986
2987// This should only be called from the main thread. Otherwise it would need
2988// the lock and should use mCurrentState rather than mDrawingState.
2989void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002990 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002991 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002992 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002993
2994 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2995}
2996
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002997void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002998{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002999 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003000#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003001 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003002#endif
3003#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003004 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003005#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003006 if (isLayerTripleBufferingDisabled())
3007 result.append(" DISABLE_TRIPLE_BUFFERING");
3008 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003009}
3010
3011void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3012{
3013 result.appendFormat("Static screen stats:\n");
3014 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3015 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3016 float percent = 100.0f *
3017 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3018 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3019 b + 1, bucketTimeSec, percent);
3020 }
3021 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3022 float percent = 100.0f *
3023 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3024 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3025 NUM_BUCKETS - 1, bucketTimeSec, percent);
3026}
3027
Brian Andersond6927fb2016-07-23 23:37:30 -07003028void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3029 result.appendFormat("Layer frame timestamps:\n");
3030
3031 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3032 const size_t count = currentLayers.size();
3033 for (size_t i=0 ; i<count ; i++) {
3034 currentLayers[i]->dumpFrameEvents(result);
3035 }
3036}
3037
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003038void SurfaceFlinger::recordBufferingStats(const char* layerName,
3039 std::vector<OccupancyTracker::Segment>&& history) {
3040 Mutex::Autolock lock(mBufferingStatsMutex);
3041 auto& stats = mBufferingStats[layerName];
3042 for (const auto& segment : history) {
3043 if (!segment.usedThirdBuffer) {
3044 stats.twoBufferTime += segment.totalTime;
3045 }
3046 if (segment.occupancyAverage < 1.0f) {
3047 stats.doubleBufferedTime += segment.totalTime;
3048 } else if (segment.occupancyAverage < 2.0f) {
3049 stats.tripleBufferedTime += segment.totalTime;
3050 }
3051 ++stats.numSegments;
3052 stats.totalTime += segment.totalTime;
3053 }
3054}
3055
3056void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3057 result.append("Buffering stats:\n");
3058 result.append(" [Layer name] <Active time> <Two buffer> "
3059 "<Double buffered> <Triple buffered>\n");
3060 Mutex::Autolock lock(mBufferingStatsMutex);
3061 typedef std::tuple<std::string, float, float, float> BufferTuple;
3062 std::map<float, BufferTuple, std::greater<float>> sorted;
3063 for (const auto& statsPair : mBufferingStats) {
3064 const char* name = statsPair.first.c_str();
3065 const BufferingStats& stats = statsPair.second;
3066 if (stats.numSegments == 0) {
3067 continue;
3068 }
3069 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3070 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3071 stats.totalTime;
3072 float doubleBufferRatio = static_cast<float>(
3073 stats.doubleBufferedTime) / stats.totalTime;
3074 float tripleBufferRatio = static_cast<float>(
3075 stats.tripleBufferedTime) / stats.totalTime;
3076 sorted.insert({activeTime, {name, twoBufferRatio,
3077 doubleBufferRatio, tripleBufferRatio}});
3078 }
3079 for (const auto& sortedPair : sorted) {
3080 float activeTime = sortedPair.first;
3081 const BufferTuple& values = sortedPair.second;
3082 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3083 std::get<0>(values).c_str(), activeTime,
3084 std::get<1>(values), std::get<2>(values),
3085 std::get<3>(values));
3086 }
3087 result.append("\n");
3088}
3089
3090void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3091 String8& result) const
3092{
3093 bool colorize = false;
3094 if (index < args.size()
3095 && (args[index] == String16("--color"))) {
3096 colorize = true;
3097 index++;
3098 }
3099
3100 Colorizer colorizer(colorize);
3101
3102 // figure out if we're stuck somewhere
3103 const nsecs_t now = systemTime();
3104 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3105 const nsecs_t inTransaction(mDebugInTransaction);
3106 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3107 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3108
3109 /*
3110 * Dump library configuration.
3111 */
3112
3113 colorizer.bold(result);
3114 result.append("Build configuration:");
3115 colorizer.reset(result);
3116 appendSfConfigString(result);
3117 appendUiConfigString(result);
3118 appendGuiConfigString(result);
3119 result.append("\n");
3120
3121 colorizer.bold(result);
3122 result.append("Sync configuration: ");
3123 colorizer.reset(result);
3124 result.append(SyncFeatures::getInstance().toString());
3125 result.append("\n");
3126
3127 colorizer.bold(result);
3128 result.append("DispSync configuration: ");
3129 colorizer.reset(result);
3130 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3131 "present offset %d ns (refresh %" PRId64 " ns)",
3132 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3133 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3134 result.append("\n");
3135
3136 // Dump static screen stats
3137 result.append("\n");
3138 dumpStaticScreenStats(result);
3139 result.append("\n");
3140
3141 dumpBufferingStats(result);
3142
3143 /*
3144 * Dump the visible layer list
3145 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003146 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003147 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003148 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003149 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003150 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003151 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003152
3153 /*
3154 * Dump Display state
3155 */
3156
3157 colorizer.bold(result);
3158 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3159 colorizer.reset(result);
3160 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3161 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3162 hw->dump(result);
3163 }
3164
3165 /*
3166 * Dump SurfaceFlinger global state
3167 */
3168
3169 colorizer.bold(result);
3170 result.append("SurfaceFlinger global state:\n");
3171 colorizer.reset(result);
3172
3173 HWComposer& hwc(getHwComposer());
3174 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3175
3176 colorizer.bold(result);
3177 result.appendFormat("EGL implementation : %s\n",
3178 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3179 colorizer.reset(result);
3180 result.appendFormat("%s\n",
3181 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3182
3183 mRenderEngine->dump(result);
3184
3185 hw->undefinedRegion.dump(result, "undefinedRegion");
3186 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3187 hw->getOrientation(), hw->isDisplayOn());
3188 result.appendFormat(
3189 " last eglSwapBuffers() time: %f us\n"
3190 " last transaction time : %f us\n"
3191 " transaction-flags : %08x\n"
3192 " refresh-rate : %f fps\n"
3193 " x-dpi : %f\n"
3194 " y-dpi : %f\n"
3195 " gpu_to_cpu_unsupported : %d\n"
3196 ,
3197 mLastSwapBufferTime/1000.0,
3198 mLastTransactionTime/1000.0,
3199 mTransactionFlags,
3200 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3201 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3202 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3203 !mGpuToCpuSupported);
3204
3205 result.appendFormat(" eglSwapBuffers time: %f us\n",
3206 inSwapBuffersDuration/1000.0);
3207
3208 result.appendFormat(" transaction time: %f us\n",
3209 inTransactionDuration/1000.0);
3210
3211 /*
3212 * VSYNC state
3213 */
3214 mEventThread->dump(result);
3215
3216 /*
3217 * Dump HWComposer state
3218 */
3219 colorizer.bold(result);
3220 result.append("h/w composer state:\n");
3221 colorizer.reset(result);
3222 result.appendFormat(" h/w composer %s and %s\n",
3223 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3224 (mDebugDisableHWC || mDebugRegion || mDaltonize
3225 || mHasColorMatrix) ? "disabled" : "enabled");
3226 hwc.dump(result);
3227
3228 /*
3229 * Dump gralloc state
3230 */
3231 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3232 alloc.dump(result);
3233}
3234
3235const Vector< sp<Layer> >&
3236SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3237 // Note: mStateLock is held here
3238 wp<IBinder> dpy;
3239 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3240 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3241 dpy = mDisplays.keyAt(i);
3242 break;
3243 }
3244 }
3245 if (dpy == NULL) {
3246 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3247 // Just use the primary display so we have something to return
3248 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3249 }
3250 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3251}
3252
3253bool SurfaceFlinger::startDdmConnection()
3254{
3255 void* libddmconnection_dso =
3256 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3257 if (!libddmconnection_dso) {
3258 return false;
3259 }
3260 void (*DdmConnection_start)(const char* name);
3261 DdmConnection_start =
3262 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3263 if (!DdmConnection_start) {
3264 dlclose(libddmconnection_dso);
3265 return false;
3266 }
3267 (*DdmConnection_start)(getServiceName());
3268 return true;
3269}
3270
3271status_t SurfaceFlinger::onTransact(
3272 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3273{
3274 switch (code) {
3275 case CREATE_CONNECTION:
3276 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003277 case BOOT_FINISHED:
3278 case CLEAR_ANIMATION_FRAME_STATS:
3279 case GET_ANIMATION_FRAME_STATS:
3280 case SET_POWER_MODE:
3281 case GET_HDR_CAPABILITIES:
3282 {
3283 // codes that require permission check
3284 IPCThreadState* ipc = IPCThreadState::self();
3285 const int pid = ipc->getCallingPid();
3286 const int uid = ipc->getCallingUid();
3287 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3288 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3289 ALOGE("Permission Denial: "
3290 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3291 return PERMISSION_DENIED;
3292 }
3293 break;
3294 }
Robert Carr1db73f62016-12-21 12:58:51 -08003295 /*
3296 * Calling setTransactionState is safe, because you need to have been
3297 * granted a reference to Client* and Handle* to do anything with it.
3298 *
3299 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3300 */
3301 case SET_TRANSACTION_STATE:
3302 case CREATE_SCOPED_CONNECTION:
3303 {
3304 break;
3305 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003306 case CAPTURE_SCREEN:
3307 {
3308 // codes that require permission check
3309 IPCThreadState* ipc = IPCThreadState::self();
3310 const int pid = ipc->getCallingPid();
3311 const int uid = ipc->getCallingUid();
3312 if ((uid != AID_GRAPHICS) &&
3313 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3314 ALOGE("Permission Denial: "
3315 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3316 return PERMISSION_DENIED;
3317 }
3318 break;
3319 }
3320 }
3321
3322 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3323 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3324 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3325 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3326 IPCThreadState* ipc = IPCThreadState::self();
3327 const int pid = ipc->getCallingPid();
3328 const int uid = ipc->getCallingUid();
3329 ALOGE("Permission Denial: "
3330 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3331 return PERMISSION_DENIED;
3332 }
3333 int n;
3334 switch (code) {
3335 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3336 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3337 return NO_ERROR;
3338 case 1002: // SHOW_UPDATES
3339 n = data.readInt32();
3340 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3341 invalidateHwcGeometry();
3342 repaintEverything();
3343 return NO_ERROR;
3344 case 1004:{ // repaint everything
3345 repaintEverything();
3346 return NO_ERROR;
3347 }
3348 case 1005:{ // force transaction
3349 setTransactionFlags(
3350 eTransactionNeeded|
3351 eDisplayTransactionNeeded|
3352 eTraversalNeeded);
3353 return NO_ERROR;
3354 }
3355 case 1006:{ // send empty update
3356 signalRefresh();
3357 return NO_ERROR;
3358 }
3359 case 1008: // toggle use of hw composer
3360 n = data.readInt32();
3361 mDebugDisableHWC = n ? 1 : 0;
3362 invalidateHwcGeometry();
3363 repaintEverything();
3364 return NO_ERROR;
3365 case 1009: // toggle use of transform hint
3366 n = data.readInt32();
3367 mDebugDisableTransformHint = n ? 1 : 0;
3368 invalidateHwcGeometry();
3369 repaintEverything();
3370 return NO_ERROR;
3371 case 1010: // interrogate.
3372 reply->writeInt32(0);
3373 reply->writeInt32(0);
3374 reply->writeInt32(mDebugRegion);
3375 reply->writeInt32(0);
3376 reply->writeInt32(mDebugDisableHWC);
3377 return NO_ERROR;
3378 case 1013: {
3379 Mutex::Autolock _l(mStateLock);
3380 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3381 reply->writeInt32(hw->getPageFlipCount());
3382 return NO_ERROR;
3383 }
3384 case 1014: {
3385 // daltonize
3386 n = data.readInt32();
3387 switch (n % 10) {
3388 case 1:
3389 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3390 break;
3391 case 2:
3392 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3393 break;
3394 case 3:
3395 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3396 break;
3397 }
3398 if (n >= 10) {
3399 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3400 } else {
3401 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3402 }
3403 mDaltonize = n > 0;
3404 invalidateHwcGeometry();
3405 repaintEverything();
3406 return NO_ERROR;
3407 }
3408 case 1015: {
3409 // apply a color matrix
3410 n = data.readInt32();
3411 mHasColorMatrix = n ? 1 : 0;
3412 if (n) {
3413 // color matrix is sent as mat3 matrix followed by vec3
3414 // offset, then packed into a mat4 where the last row is
3415 // the offset and extra values are 0
3416 for (size_t i = 0 ; i < 4; i++) {
3417 for (size_t j = 0; j < 4; j++) {
3418 mColorMatrix[i][j] = data.readFloat();
3419 }
3420 }
3421 } else {
3422 mColorMatrix = mat4();
3423 }
3424 invalidateHwcGeometry();
3425 repaintEverything();
3426 return NO_ERROR;
3427 }
3428 // This is an experimental interface
3429 // Needs to be shifted to proper binder interface when we productize
3430 case 1016: {
3431 n = data.readInt32();
3432 mPrimaryDispSync.setRefreshSkipCount(n);
3433 return NO_ERROR;
3434 }
3435 case 1017: {
3436 n = data.readInt32();
3437 mForceFullDamage = static_cast<bool>(n);
3438 return NO_ERROR;
3439 }
3440 case 1018: { // Modify Choreographer's phase offset
3441 n = data.readInt32();
3442 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3443 return NO_ERROR;
3444 }
3445 case 1019: { // Modify SurfaceFlinger's phase offset
3446 n = data.readInt32();
3447 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3448 return NO_ERROR;
3449 }
3450 case 1020: { // Layer updates interceptor
3451 n = data.readInt32();
3452 if (n) {
3453 ALOGV("Interceptor enabled");
3454 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3455 }
3456 else{
3457 ALOGV("Interceptor disabled");
3458 mInterceptor.disable();
3459 }
3460 return NO_ERROR;
3461 }
3462 case 1021: { // Disable HWC virtual displays
3463 n = data.readInt32();
3464 mUseHwcVirtualDisplays = !n;
3465 return NO_ERROR;
3466 }
3467 }
3468 }
3469 return err;
3470}
3471
3472void SurfaceFlinger::repaintEverything() {
3473 android_atomic_or(1, &mRepaintEverything);
3474 signalTransaction();
3475}
3476
3477// ---------------------------------------------------------------------------
3478// Capture screen into an IGraphiBufferProducer
3479// ---------------------------------------------------------------------------
3480
3481/* The code below is here to handle b/8734824
3482 *
3483 * We create a IGraphicBufferProducer wrapper that forwards all calls
3484 * from the surfaceflinger thread to the calling binder thread, where they
3485 * are executed. This allows the calling thread in the calling process to be
3486 * reused and not depend on having "enough" binder threads to handle the
3487 * requests.
3488 */
3489class GraphicProducerWrapper : public BBinder, public MessageHandler {
3490 /* Parts of GraphicProducerWrapper are run on two different threads,
3491 * communicating by sending messages via Looper but also by shared member
3492 * data. Coherence maintenance is subtle and in places implicit (ugh).
3493 *
3494 * Don't rely on Looper's sendMessage/handleMessage providing
3495 * release/acquire semantics for any data not actually in the Message.
3496 * Data going from surfaceflinger to binder threads needs to be
3497 * synchronized explicitly.
3498 *
3499 * Barrier open/wait do provide release/acquire semantics. This provides
3500 * implicit synchronization for data coming back from binder to
3501 * surfaceflinger threads.
3502 */
3503
3504 sp<IGraphicBufferProducer> impl;
3505 sp<Looper> looper;
3506 status_t result;
3507 bool exitPending;
3508 bool exitRequested;
3509 Barrier barrier;
3510 uint32_t code;
3511 Parcel const* data;
3512 Parcel* reply;
3513
3514 enum {
3515 MSG_API_CALL,
3516 MSG_EXIT
3517 };
3518
3519 /*
3520 * Called on surfaceflinger thread. This is called by our "fake"
3521 * BpGraphicBufferProducer. We package the data and reply Parcel and
3522 * forward them to the binder thread.
3523 */
3524 virtual status_t transact(uint32_t code,
3525 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3526 this->code = code;
3527 this->data = &data;
3528 this->reply = reply;
3529 if (exitPending) {
3530 // if we've exited, we run the message synchronously right here.
3531 // note (JH): as far as I can tell from looking at the code, this
3532 // never actually happens. if it does, i'm not sure if it happens
3533 // on the surfaceflinger or binder thread.
3534 handleMessage(Message(MSG_API_CALL));
3535 } else {
3536 barrier.close();
3537 // Prevent stores to this->{code, data, reply} from being
3538 // reordered later than the construction of Message.
3539 atomic_thread_fence(memory_order_release);
3540 looper->sendMessage(this, Message(MSG_API_CALL));
3541 barrier.wait();
3542 }
3543 return result;
3544 }
3545
3546 /*
3547 * here we run on the binder thread. All we've got to do is
3548 * call the real BpGraphicBufferProducer.
3549 */
3550 virtual void handleMessage(const Message& message) {
3551 int what = message.what;
3552 // Prevent reads below from happening before the read from Message
3553 atomic_thread_fence(memory_order_acquire);
3554 if (what == MSG_API_CALL) {
3555 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3556 barrier.open();
3557 } else if (what == MSG_EXIT) {
3558 exitRequested = true;
3559 }
3560 }
3561
3562public:
3563 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3564 : impl(impl),
3565 looper(new Looper(true)),
3566 result(NO_ERROR),
3567 exitPending(false),
3568 exitRequested(false),
3569 code(0),
3570 data(NULL),
3571 reply(NULL)
3572 {}
3573
3574 // Binder thread
3575 status_t waitForResponse() {
3576 do {
3577 looper->pollOnce(-1);
3578 } while (!exitRequested);
3579 return result;
3580 }
3581
3582 // Client thread
3583 void exit(status_t result) {
3584 this->result = result;
3585 exitPending = true;
3586 // Ensure this->result is visible to the binder thread before it
3587 // handles the message.
3588 atomic_thread_fence(memory_order_release);
3589 looper->sendMessage(this, Message(MSG_EXIT));
3590 }
3591};
3592
3593
3594status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3595 const sp<IGraphicBufferProducer>& producer,
3596 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003597 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003598 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3599
3600 if (CC_UNLIKELY(display == 0))
3601 return BAD_VALUE;
3602
3603 if (CC_UNLIKELY(producer == 0))
3604 return BAD_VALUE;
3605
3606 // if we have secure windows on this display, never allow the screen capture
3607 // unless the producer interface is local (i.e.: we can take a screenshot for
3608 // ourselves).
3609 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3610
3611 // Convert to surfaceflinger's internal rotation type.
3612 Transform::orientation_flags rotationFlags;
3613 switch (rotation) {
3614 case ISurfaceComposer::eRotateNone:
3615 rotationFlags = Transform::ROT_0;
3616 break;
3617 case ISurfaceComposer::eRotate90:
3618 rotationFlags = Transform::ROT_90;
3619 break;
3620 case ISurfaceComposer::eRotate180:
3621 rotationFlags = Transform::ROT_180;
3622 break;
3623 case ISurfaceComposer::eRotate270:
3624 rotationFlags = Transform::ROT_270;
3625 break;
3626 default:
3627 rotationFlags = Transform::ROT_0;
3628 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3629 break;
3630 }
3631
3632 class MessageCaptureScreen : public MessageBase {
3633 SurfaceFlinger* flinger;
3634 sp<IBinder> display;
3635 sp<IGraphicBufferProducer> producer;
3636 Rect sourceCrop;
3637 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003638 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003639 bool useIdentityTransform;
3640 Transform::orientation_flags rotation;
3641 status_t result;
3642 bool isLocalScreenshot;
3643 public:
3644 MessageCaptureScreen(SurfaceFlinger* flinger,
3645 const sp<IBinder>& display,
3646 const sp<IGraphicBufferProducer>& producer,
3647 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003648 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003649 bool useIdentityTransform,
3650 Transform::orientation_flags rotation,
3651 bool isLocalScreenshot)
3652 : flinger(flinger), display(display), producer(producer),
3653 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3654 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3655 useIdentityTransform(useIdentityTransform),
3656 rotation(rotation), result(PERMISSION_DENIED),
3657 isLocalScreenshot(isLocalScreenshot)
3658 {
3659 }
3660 status_t getResult() const {
3661 return result;
3662 }
3663 virtual bool handler() {
3664 Mutex::Autolock _l(flinger->mStateLock);
3665 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3666 result = flinger->captureScreenImplLocked(hw, producer,
3667 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3668 useIdentityTransform, rotation, isLocalScreenshot);
3669 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3670 return true;
3671 }
3672 };
3673
3674 // this creates a "fake" BBinder which will serve as a "fake" remote
3675 // binder to receive the marshaled calls and forward them to the
3676 // real remote (a BpGraphicBufferProducer)
3677 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3678
3679 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3680 // which does the marshaling work forwards to our "fake remote" above.
3681 sp<MessageBase> msg = new MessageCaptureScreen(this,
3682 display, IGraphicBufferProducer::asInterface( wrapper ),
3683 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3684 useIdentityTransform, rotationFlags, isLocalScreenshot);
3685
3686 status_t res = postMessageAsync(msg);
3687 if (res == NO_ERROR) {
3688 res = wrapper->waitForResponse();
3689 }
3690 return res;
3691}
3692
3693
3694void SurfaceFlinger::renderScreenImplLocked(
3695 const sp<const DisplayDevice>& hw,
3696 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003697 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003698 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3699{
3700 ATRACE_CALL();
3701 RenderEngine& engine(getRenderEngine());
3702
3703 // get screen geometry
3704 const int32_t hw_w = hw->getWidth();
3705 const int32_t hw_h = hw->getHeight();
3706 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3707 static_cast<int32_t>(reqHeight) != hw_h;
3708
3709 // if a default or invalid sourceCrop is passed in, set reasonable values
3710 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3711 !sourceCrop.isValid()) {
3712 sourceCrop.setLeftTop(Point(0, 0));
3713 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3714 }
3715
3716 // ensure that sourceCrop is inside screen
3717 if (sourceCrop.left < 0) {
3718 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3719 }
3720 if (sourceCrop.right > hw_w) {
3721 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3722 }
3723 if (sourceCrop.top < 0) {
3724 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3725 }
3726 if (sourceCrop.bottom > hw_h) {
3727 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3728 }
3729
3730 // make sure to clear all GL error flags
3731 engine.checkErrors();
3732
3733 // set-up our viewport
3734 engine.setViewportAndProjection(
3735 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3736 engine.disableTexturing();
3737
3738 // redraw the screen entirely...
3739 engine.clearWithColor(0, 0, 0, 1);
3740
Robert Carr1f0a16a2016-10-24 16:27:39 -07003741 // We loop through the first level of layers without traversing,
3742 // as we need to interpret min/max layer Z in the top level Z space.
3743 for (const auto& layer : mDrawingState.layersSortedByZ) {
3744 if (layer->getLayerStack() != hw->getLayerStack()) {
3745 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003746 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003747 const Layer::State& state(layer->getDrawingState());
3748 if (state.z < minLayerZ || state.z > maxLayerZ) {
3749 continue;
3750 }
3751 layer->traverseInZOrder([&](Layer* layer) {
3752 if (!layer->isVisible()) {
3753 return;
3754 }
3755 if (filtering) layer->setFiltering(true);
3756 layer->draw(hw, useIdentityTransform);
3757 if (filtering) layer->setFiltering(false);
3758 });
3759 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003760
3761 // compositionComplete is needed for older driver
3762 hw->compositionComplete();
3763 hw->setViewportAndProjection();
3764}
3765
3766
3767status_t SurfaceFlinger::captureScreenImplLocked(
3768 const sp<const DisplayDevice>& hw,
3769 const sp<IGraphicBufferProducer>& producer,
3770 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003771 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003772 bool useIdentityTransform, Transform::orientation_flags rotation,
3773 bool isLocalScreenshot)
3774{
3775 ATRACE_CALL();
3776
3777 // get screen geometry
3778 uint32_t hw_w = hw->getWidth();
3779 uint32_t hw_h = hw->getHeight();
3780
3781 if (rotation & Transform::ROT_90) {
3782 std::swap(hw_w, hw_h);
3783 }
3784
3785 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3786 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3787 reqWidth, reqHeight, hw_w, hw_h);
3788 return BAD_VALUE;
3789 }
3790
3791 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3792 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3793
3794 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003795 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003796 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003797 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3798 (state.z < minLayerZ || state.z > maxLayerZ)) {
3799 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003800 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003801 layer->traverseInZOrder([&](Layer *layer) {
3802 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3803 layer->isSecure());
3804 });
3805 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003806
3807 if (!isLocalScreenshot && secureLayerIsVisible) {
3808 ALOGW("FB is protected: PERMISSION_DENIED");
3809 return PERMISSION_DENIED;
3810 }
3811
3812 // create a surface (because we're a producer, and we need to
3813 // dequeue/queue a buffer)
3814 sp<Surface> sur = new Surface(producer, false);
3815 ANativeWindow* window = sur.get();
3816
3817 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3818 if (result == NO_ERROR) {
3819 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3820 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3821
3822 int err = 0;
3823 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3824 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3825 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3826 err |= native_window_set_usage(window, usage);
3827
3828 if (err == NO_ERROR) {
3829 ANativeWindowBuffer* buffer;
3830 /* TODO: Once we have the sync framework everywhere this can use
3831 * server-side waits on the fence that dequeueBuffer returns.
3832 */
3833 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3834 if (result == NO_ERROR) {
3835 int syncFd = -1;
3836 // create an EGLImage from the buffer so we can later
3837 // turn it into a texture
3838 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3839 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3840 if (image != EGL_NO_IMAGE_KHR) {
3841 // this binds the given EGLImage as a framebuffer for the
3842 // duration of this scope.
3843 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3844 if (imageBond.getStatus() == NO_ERROR) {
3845 // this will in fact render into our dequeued buffer
3846 // via an FBO, which means we didn't have to create
3847 // an EGLSurface and therefore we're not
3848 // dependent on the context's EGLConfig.
3849 renderScreenImplLocked(
3850 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3851 useIdentityTransform, rotation);
3852
3853 // Attempt to create a sync khr object that can produce a sync point. If that
3854 // isn't available, create a non-dupable sync object in the fallback path and
3855 // wait on it directly.
3856 EGLSyncKHR sync;
3857 if (!DEBUG_SCREENSHOTS) {
3858 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3859 // native fence fd will not be populated until flush() is done.
3860 getRenderEngine().flush();
3861 } else {
3862 sync = EGL_NO_SYNC_KHR;
3863 }
3864 if (sync != EGL_NO_SYNC_KHR) {
3865 // get the sync fd
3866 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3867 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3868 ALOGW("captureScreen: failed to dup sync khr object");
3869 syncFd = -1;
3870 }
3871 eglDestroySyncKHR(mEGLDisplay, sync);
3872 } else {
3873 // fallback path
3874 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3875 if (sync != EGL_NO_SYNC_KHR) {
3876 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3877 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3878 EGLint eglErr = eglGetError();
3879 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3880 ALOGW("captureScreen: fence wait timed out");
3881 } else {
3882 ALOGW_IF(eglErr != EGL_SUCCESS,
3883 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3884 }
3885 eglDestroySyncKHR(mEGLDisplay, sync);
3886 } else {
3887 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3888 }
3889 }
3890 if (DEBUG_SCREENSHOTS) {
3891 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3892 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3893 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3894 hw, minLayerZ, maxLayerZ);
3895 delete [] pixels;
3896 }
3897
3898 } else {
3899 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3900 result = INVALID_OPERATION;
3901 window->cancelBuffer(window, buffer, syncFd);
3902 buffer = NULL;
3903 }
3904 // destroy our image
3905 eglDestroyImageKHR(mEGLDisplay, image);
3906 } else {
3907 result = BAD_VALUE;
3908 }
3909 if (buffer) {
3910 // queueBuffer takes ownership of syncFd
3911 result = window->queueBuffer(window, buffer, syncFd);
3912 }
3913 }
3914 } else {
3915 result = BAD_VALUE;
3916 }
3917 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3918 }
3919
3920 return result;
3921}
3922
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003923void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003924 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003925 if (DEBUG_SCREENSHOTS) {
3926 for (size_t y=0 ; y<h ; y++) {
3927 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3928 for (size_t x=0 ; x<w ; x++) {
3929 if (p[x] != 0xFF000000) return;
3930 }
3931 }
3932 ALOGE("*** we just took a black screenshot ***\n"
3933 "requested minz=%d, maxz=%d, layerStack=%d",
3934 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003935 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003936 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003937 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003938 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3939 state.z <= maxLayerZ) {
3940 layer->traverseInZOrder([&](Layer* layer) {
3941 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3942 layer->isVisible() ? '+' : '-',
3943 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003944 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003945 i++;
3946 });
3947 }
3948 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003949 }
3950}
3951
3952// ---------------------------------------------------------------------------
3953
Robert Carr2047fae2016-11-28 14:09:09 -08003954void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3955 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003956}
3957
Robert Carr2047fae2016-11-28 14:09:09 -08003958void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3959 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003960}
3961
3962}; // namespace android
3963
3964
3965#if defined(__gl_h_)
3966#error "don't include gl/gl.h in this file"
3967#endif
3968
3969#if defined(__gl2_h_)
3970#error "don't include gl2/gl2.h in this file"
3971#endif