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