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