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