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