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