blob: 072de8177306e05a806b1672cf30a03aadd079bb [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 Ceballos69a1a382016-03-30 15:28:05 -0700946#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -0800947 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Pablo Ceballos69a1a382016-03-30 15:28:05 -0700948#else
949 nsecs_t refreshStartTime = 0;
950#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800951 static nsecs_t previousExpectedPresent = 0;
952 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
953 static bool previousFrameMissed = false;
954 bool frameMissed = (expectedPresent == previousExpectedPresent);
955 if (frameMissed != previousFrameMissed) {
956 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
957 }
958 previousFrameMissed = frameMissed;
959
960 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
961 // Latch buffers, but don't send anything to HWC, then signal another
962 // wakeup for the next vsync
963 preComposition();
964 repaintEverything();
965 } else {
966 preComposition();
967 rebuildLayerStacks();
968 setUpHWComposer();
969 doDebugFlashRegions();
970 doComposition();
Pablo Ceballos40845df2016-01-25 17:41:15 -0800971 postComposition(refreshStartTime);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800972 }
973
974 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
975}
976
977void SurfaceFlinger::doDebugFlashRegions()
978{
979 // is debugging enabled
980 if (CC_LIKELY(!mDebugRegion))
981 return;
982
983 const bool repaintEverything = mRepaintEverything;
984 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
985 const sp<DisplayDevice>& hw(mDisplays[dpy]);
986 if (hw->isDisplayOn()) {
987 // transform the dirty region into this screen's coordinate space
988 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
989 if (!dirtyRegion.isEmpty()) {
990 // redraw the whole screen
991 doComposeSurfaces(hw, Region(hw->bounds()));
992
993 // and draw the dirty region
994 const int32_t height = hw->getHeight();
995 RenderEngine& engine(getRenderEngine());
996 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
997
998 hw->compositionComplete();
999 hw->swapBuffers(getHwComposer());
1000 }
1001 }
1002 }
1003
1004 postFramebuffer();
1005
1006 if (mDebugRegion > 1) {
1007 usleep(mDebugRegion * 1000);
1008 }
1009
1010 HWComposer& hwc(getHwComposer());
1011 if (hwc.initCheck() == NO_ERROR) {
1012 status_t err = hwc.prepare();
1013 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1014 }
1015}
1016
1017void SurfaceFlinger::preComposition()
1018{
1019 bool needExtraInvalidate = false;
1020 const LayerVector& layers(mDrawingState.layersSortedByZ);
1021 const size_t count = layers.size();
1022 for (size_t i=0 ; i<count ; i++) {
1023 if (layers[i]->onPreComposition()) {
1024 needExtraInvalidate = true;
1025 }
1026 }
1027 if (needExtraInvalidate) {
1028 signalLayerUpdate();
1029 }
1030}
1031
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001032#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001033void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001034#else
1035void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1036#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001037{
1038 const LayerVector& layers(mDrawingState.layersSortedByZ);
1039 const size_t count = layers.size();
1040 for (size_t i=0 ; i<count ; i++) {
1041 layers[i]->onPostComposition();
1042 }
1043
1044 const HWComposer& hwc = getHwComposer();
1045 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1046
1047 if (presentFence->isValid()) {
1048 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1049 enableHardwareVsync();
1050 } else {
1051 disableHardwareVsync(false);
1052 }
1053 }
1054
1055 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1056 if (kIgnorePresentFences) {
1057 if (hw->isDisplayOn()) {
1058 enableHardwareVsync();
1059 }
1060 }
1061
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001062#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08001063 mFenceTracker.addFrame(refreshStartTime, presentFence,
1064 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
Pablo Ceballos69a1a382016-03-30 15:28:05 -07001065#endif
Pablo Ceballos40845df2016-01-25 17:41:15 -08001066
Dan Stoza9e56aa02015-11-02 13:00:03 -08001067 if (mAnimCompositionPending) {
1068 mAnimCompositionPending = false;
1069
1070 if (presentFence->isValid()) {
1071 mAnimFrameTracker.setActualPresentFence(presentFence);
1072 } else {
1073 // The HWC doesn't support present fences, so use the refresh
1074 // timestamp instead.
1075 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1076 mAnimFrameTracker.setActualPresentTime(presentTime);
1077 }
1078 mAnimFrameTracker.advanceFrame();
1079 }
1080
1081 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1082 return;
1083 }
1084
1085 nsecs_t currentTime = systemTime();
1086 if (mHasPoweredOff) {
1087 mHasPoweredOff = false;
1088 } else {
1089 nsecs_t period = mPrimaryDispSync.getPeriod();
1090 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1091 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1092 if (numPeriods < NUM_BUCKETS - 1) {
1093 mFrameBuckets[numPeriods] += elapsedTime;
1094 } else {
1095 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1096 }
1097 mTotalTime += elapsedTime;
1098 }
1099 mLastSwapTime = currentTime;
1100}
1101
1102void SurfaceFlinger::rebuildLayerStacks() {
1103 // rebuild the visible layer list per screen
1104 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1105 ATRACE_CALL();
1106 mVisibleRegionsDirty = false;
1107 invalidateHwcGeometry();
1108
1109 const LayerVector& layers(mDrawingState.layersSortedByZ);
1110 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1111 Region opaqueRegion;
1112 Region dirtyRegion;
1113 Vector< sp<Layer> > layersSortedByZ;
1114 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1115 const Transform& tr(hw->getTransform());
1116 const Rect bounds(hw->getBounds());
1117 if (hw->isDisplayOn()) {
1118 SurfaceFlinger::computeVisibleRegions(layers,
1119 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1120
1121 const size_t count = layers.size();
1122 for (size_t i=0 ; i<count ; i++) {
1123 const sp<Layer>& layer(layers[i]);
1124 const Layer::State& s(layer->getDrawingState());
1125 if (s.layerStack == hw->getLayerStack()) {
1126 Region drawRegion(tr.transform(
1127 layer->visibleNonTransparentRegion));
1128 drawRegion.andSelf(bounds);
1129 if (!drawRegion.isEmpty()) {
1130 layersSortedByZ.add(layer);
1131 }
1132 }
1133 }
1134 }
1135 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1136 hw->undefinedRegion.set(bounds);
1137 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1138 hw->dirtyRegion.orSelf(dirtyRegion);
1139 }
1140 }
1141}
1142
1143void SurfaceFlinger::setUpHWComposer() {
1144 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1145 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1146 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1147 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1148
1149 // If nothing has changed (!dirty), don't recompose.
1150 // If something changed, but we don't currently have any visible layers,
1151 // and didn't when we last did a composition, then skip it this time.
1152 // The second rule does two things:
1153 // - When all layers are removed from a display, we'll emit one black
1154 // frame, then nothing more until we get new layers.
1155 // - When a display is created with a private layer stack, we won't
1156 // emit any black frames until a layer is added to the layer stack.
1157 bool mustRecompose = dirty && !(empty && wasEmpty);
1158
1159 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1160 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1161 mustRecompose ? "doing" : "skipping",
1162 dirty ? "+" : "-",
1163 empty ? "+" : "-",
1164 wasEmpty ? "+" : "-");
1165
1166 mDisplays[dpy]->beginFrame(mustRecompose);
1167
1168 if (mustRecompose) {
1169 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1170 }
1171 }
1172
1173 HWComposer& hwc(getHwComposer());
1174 if (hwc.initCheck() == NO_ERROR) {
1175 // build the h/w work list
1176 if (CC_UNLIKELY(mHwWorkListDirty)) {
1177 mHwWorkListDirty = false;
1178 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1179 sp<const DisplayDevice> hw(mDisplays[dpy]);
1180 const int32_t id = hw->getHwcDisplayId();
1181 if (id >= 0) {
1182 const Vector< sp<Layer> >& currentLayers(
1183 hw->getVisibleLayersSortedByZ());
1184 const size_t count = currentLayers.size();
1185 if (hwc.createWorkList(id, count) == NO_ERROR) {
1186 HWComposer::LayerListIterator cur = hwc.begin(id);
1187 const HWComposer::LayerListIterator end = hwc.end(id);
1188 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1189 const sp<Layer>& layer(currentLayers[i]);
1190 layer->setGeometry(hw, *cur);
1191 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1192 cur->setSkip(true);
1193 }
1194 }
1195 }
1196 }
1197 }
1198 }
1199
1200 // set the per-frame data
1201 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1202 sp<const DisplayDevice> hw(mDisplays[dpy]);
1203 const int32_t id = hw->getHwcDisplayId();
1204 if (id >= 0) {
1205 const Vector< sp<Layer> >& currentLayers(
1206 hw->getVisibleLayersSortedByZ());
1207 const size_t count = currentLayers.size();
1208 HWComposer::LayerListIterator cur = hwc.begin(id);
1209 const HWComposer::LayerListIterator end = hwc.end(id);
1210 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1211 /*
1212 * update the per-frame h/w composer data for each layer
1213 * and build the transparent region of the FB
1214 */
1215 const sp<Layer>& layer(currentLayers[i]);
1216 layer->setPerFrameData(hw, *cur);
1217 }
1218 }
1219 }
1220
1221 // If possible, attempt to use the cursor overlay on each display.
1222 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1223 sp<const DisplayDevice> hw(mDisplays[dpy]);
1224 const int32_t id = hw->getHwcDisplayId();
1225 if (id >= 0) {
1226 const Vector< sp<Layer> >& currentLayers(
1227 hw->getVisibleLayersSortedByZ());
1228 const size_t count = currentLayers.size();
1229 HWComposer::LayerListIterator cur = hwc.begin(id);
1230 const HWComposer::LayerListIterator end = hwc.end(id);
1231 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1232 const sp<Layer>& layer(currentLayers[i]);
1233 if (layer->isPotentialCursor()) {
1234 cur->setIsCursorLayerHint();
1235 break;
1236 }
1237 }
1238 }
1239 }
1240
1241 status_t err = hwc.prepare();
1242 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1243
1244 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1245 sp<const DisplayDevice> hw(mDisplays[dpy]);
1246 hw->prepareFrame(hwc);
1247 }
1248 }
1249}
1250
1251void SurfaceFlinger::doComposition() {
1252 ATRACE_CALL();
1253 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1254 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1255 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1256 if (hw->isDisplayOn()) {
1257 // transform the dirty region into this screen's coordinate space
1258 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1259
1260 // repaint the framebuffer (if needed)
1261 doDisplayComposition(hw, dirtyRegion);
1262
1263 hw->dirtyRegion.clear();
1264 hw->flip(hw->swapRegion);
1265 hw->swapRegion.clear();
1266 }
1267 // inform the h/w that we're done compositing
1268 hw->compositionComplete();
1269 }
1270 postFramebuffer();
1271}
1272
1273void SurfaceFlinger::postFramebuffer()
1274{
1275 ATRACE_CALL();
1276
1277 const nsecs_t now = systemTime();
1278 mDebugInSwapBuffers = now;
1279
1280 HWComposer& hwc(getHwComposer());
1281 if (hwc.initCheck() == NO_ERROR) {
1282 if (!hwc.supportsFramebufferTarget()) {
1283 // EGL spec says:
1284 // "surface must be bound to the calling thread's current context,
1285 // for the current rendering API."
1286 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1287 }
1288 hwc.commit();
1289 }
1290
1291 // make the default display current because the VirtualDisplayDevice code cannot
1292 // deal with dequeueBuffer() being called outside of the composition loop; however
1293 // the code below can call glFlush() which is allowed (and does in some case) call
1294 // dequeueBuffer().
1295 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1296
1297 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1298 sp<const DisplayDevice> hw(mDisplays[dpy]);
1299 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1300 hw->onSwapBuffersCompleted(hwc);
1301 const size_t count = currentLayers.size();
1302 int32_t id = hw->getHwcDisplayId();
1303 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1304 HWComposer::LayerListIterator cur = hwc.begin(id);
1305 const HWComposer::LayerListIterator end = hwc.end(id);
1306 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1307 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1308 }
1309 } else {
1310 for (size_t i = 0; i < count; i++) {
1311 currentLayers[i]->onLayerDisplayed(hw, NULL);
1312 }
1313 }
1314 }
1315
1316 mLastSwapBufferTime = systemTime() - now;
1317 mDebugInSwapBuffers = 0;
1318
1319 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1320 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1321 logFrameStats();
1322 }
1323}
1324
1325void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1326{
1327 ATRACE_CALL();
1328
1329 // here we keep a copy of the drawing state (that is the state that's
1330 // going to be overwritten by handleTransactionLocked()) outside of
1331 // mStateLock so that the side-effects of the State assignment
1332 // don't happen with mStateLock held (which can cause deadlocks).
1333 State drawingState(mDrawingState);
1334
1335 Mutex::Autolock _l(mStateLock);
1336 const nsecs_t now = systemTime();
1337 mDebugInTransaction = now;
1338
1339 // Here we're guaranteed that some transaction flags are set
1340 // so we can call handleTransactionLocked() unconditionally.
1341 // We call getTransactionFlags(), which will also clear the flags,
1342 // with mStateLock held to guarantee that mCurrentState won't change
1343 // until the transaction is committed.
1344
1345 transactionFlags = getTransactionFlags(eTransactionMask);
1346 handleTransactionLocked(transactionFlags);
1347
1348 mLastTransactionTime = systemTime() - now;
1349 mDebugInTransaction = 0;
1350 invalidateHwcGeometry();
1351 // here the transaction has been committed
1352}
1353
1354void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1355{
1356 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1357 const size_t count = currentLayers.size();
1358
1359 // Notify all layers of available frames
1360 for (size_t i = 0; i < count; ++i) {
1361 currentLayers[i]->notifyAvailableFrames();
1362 }
1363
1364 /*
1365 * Traversal of the children
1366 * (perform the transaction for each of them if needed)
1367 */
1368
1369 if (transactionFlags & eTraversalNeeded) {
1370 for (size_t i=0 ; i<count ; i++) {
1371 const sp<Layer>& layer(currentLayers[i]);
1372 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1373 if (!trFlags) continue;
1374
1375 const uint32_t flags = layer->doTransaction(0);
1376 if (flags & Layer::eVisibleRegion)
1377 mVisibleRegionsDirty = true;
1378 }
1379 }
1380
1381 /*
1382 * Perform display own transactions if needed
1383 */
1384
1385 if (transactionFlags & eDisplayTransactionNeeded) {
1386 // here we take advantage of Vector's copy-on-write semantics to
1387 // improve performance by skipping the transaction entirely when
1388 // know that the lists are identical
1389 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1390 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1391 if (!curr.isIdenticalTo(draw)) {
1392 mVisibleRegionsDirty = true;
1393 const size_t cc = curr.size();
1394 size_t dc = draw.size();
1395
1396 // find the displays that were removed
1397 // (ie: in drawing state but not in current state)
1398 // also handle displays that changed
1399 // (ie: displays that are in both lists)
1400 for (size_t i=0 ; i<dc ; i++) {
1401 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1402 if (j < 0) {
1403 // in drawing state but not in current state
1404 if (!draw[i].isMainDisplay()) {
1405 // Call makeCurrent() on the primary display so we can
1406 // be sure that nothing associated with this display
1407 // is current.
1408 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1409 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1410 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1411 if (hw != NULL)
1412 hw->disconnect(getHwComposer());
1413 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1414 mEventThread->onHotplugReceived(draw[i].type, false);
1415 mDisplays.removeItem(draw.keyAt(i));
1416 } else {
1417 ALOGW("trying to remove the main display");
1418 }
1419 } else {
1420 // this display is in both lists. see if something changed.
1421 const DisplayDeviceState& state(curr[j]);
1422 const wp<IBinder>& display(curr.keyAt(j));
1423 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1424 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1425 if (state_binder != draw_binder) {
1426 // changing the surface is like destroying and
1427 // recreating the DisplayDevice, so we just remove it
1428 // from the drawing state, so that it get re-added
1429 // below.
1430 sp<DisplayDevice> hw(getDisplayDevice(display));
1431 if (hw != NULL)
1432 hw->disconnect(getHwComposer());
1433 mDisplays.removeItem(display);
1434 mDrawingState.displays.removeItemsAt(i);
1435 dc--; i--;
1436 // at this point we must loop to the next item
1437 continue;
1438 }
1439
1440 const sp<DisplayDevice> disp(getDisplayDevice(display));
1441 if (disp != NULL) {
1442 if (state.layerStack != draw[i].layerStack) {
1443 disp->setLayerStack(state.layerStack);
1444 }
1445 if ((state.orientation != draw[i].orientation)
1446 || (state.viewport != draw[i].viewport)
1447 || (state.frame != draw[i].frame))
1448 {
1449 disp->setProjection(state.orientation,
1450 state.viewport, state.frame);
1451 }
1452 if (state.width != draw[i].width || state.height != draw[i].height) {
1453 disp->setDisplaySize(state.width, state.height);
1454 }
1455 }
1456 }
1457 }
1458
1459 // find displays that were added
1460 // (ie: in current state but not in drawing state)
1461 for (size_t i=0 ; i<cc ; i++) {
1462 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1463 const DisplayDeviceState& state(curr[i]);
1464
1465 sp<DisplaySurface> dispSurface;
1466 sp<IGraphicBufferProducer> producer;
1467 sp<IGraphicBufferProducer> bqProducer;
1468 sp<IGraphicBufferConsumer> bqConsumer;
1469 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1470 new GraphicBufferAlloc());
1471
1472 int32_t hwcDisplayId = -1;
1473 if (state.isVirtualDisplay()) {
1474 // Virtual displays without a surface are dormant:
1475 // they have external state (layer stack, projection,
1476 // etc.) but no internal state (i.e. a DisplayDevice).
1477 if (state.surface != NULL) {
1478
1479 int width = 0;
1480 int status = state.surface->query(
1481 NATIVE_WINDOW_WIDTH, &width);
1482 ALOGE_IF(status != NO_ERROR,
1483 "Unable to query width (%d)", status);
1484 int height = 0;
1485 status = state.surface->query(
1486 NATIVE_WINDOW_HEIGHT, &height);
1487 ALOGE_IF(status != NO_ERROR,
1488 "Unable to query height (%d)", status);
1489 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1490 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1491 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1492 hwcDisplayId = allocateHwcDisplayId(state.type);
1493 }
1494
1495 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1496 *mHwc, hwcDisplayId, state.surface,
1497 bqProducer, bqConsumer, state.displayName);
1498
1499 dispSurface = vds;
1500 producer = vds;
1501 }
1502 } else {
1503 ALOGE_IF(state.surface!=NULL,
1504 "adding a supported display, but rendering "
1505 "surface is provided (%p), ignoring it",
1506 state.surface.get());
1507 hwcDisplayId = allocateHwcDisplayId(state.type);
1508 // for supported (by hwc) displays we provide our
1509 // own rendering surface
1510 dispSurface = new FramebufferSurface(*mHwc, state.type,
1511 bqConsumer);
1512 producer = bqProducer;
1513 }
1514
1515 const wp<IBinder>& display(curr.keyAt(i));
1516 if (dispSurface != NULL) {
1517 sp<DisplayDevice> hw = new DisplayDevice(this,
1518 state.type, hwcDisplayId,
1519 mHwc->getFormat(hwcDisplayId), state.isSecure,
1520 display, dispSurface, producer,
1521 mRenderEngine->getEGLConfig());
1522 hw->setLayerStack(state.layerStack);
1523 hw->setProjection(state.orientation,
1524 state.viewport, state.frame);
1525 hw->setDisplayName(state.displayName);
1526 mDisplays.add(display, hw);
1527 if (state.isVirtualDisplay()) {
1528 if (hwcDisplayId >= 0) {
1529 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1530 hw->getWidth(), hw->getHeight(),
1531 hw->getFormat());
1532 }
1533 } else {
1534 mEventThread->onHotplugReceived(state.type, true);
1535 }
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1543 // The transform hint might have changed for some layers
1544 // (either because a display has changed, or because a layer
1545 // as changed).
1546 //
1547 // Walk through all the layers in currentLayers,
1548 // and update their transform hint.
1549 //
1550 // If a layer is visible only on a single display, then that
1551 // display is used to calculate the hint, otherwise we use the
1552 // default display.
1553 //
1554 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1555 // the hint is set before we acquire a buffer from the surface texture.
1556 //
1557 // NOTE: layer transactions have taken place already, so we use their
1558 // drawing state. However, SurfaceFlinger's own transaction has not
1559 // happened yet, so we must use the current state layer list
1560 // (soon to become the drawing state list).
1561 //
1562 sp<const DisplayDevice> disp;
1563 uint32_t currentlayerStack = 0;
1564 for (size_t i=0; i<count; i++) {
1565 // NOTE: we rely on the fact that layers are sorted by
1566 // layerStack first (so we don't have to traverse the list
1567 // of displays for every layer).
1568 const sp<Layer>& layer(currentLayers[i]);
1569 uint32_t layerStack = layer->getDrawingState().layerStack;
1570 if (i==0 || currentlayerStack != layerStack) {
1571 currentlayerStack = layerStack;
1572 // figure out if this layerstack is mirrored
1573 // (more than one display) if so, pick the default display,
1574 // if not, pick the only display it's on.
1575 disp.clear();
1576 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1577 sp<const DisplayDevice> hw(mDisplays[dpy]);
1578 if (hw->getLayerStack() == currentlayerStack) {
1579 if (disp == NULL) {
1580 disp = hw;
1581 } else {
1582 disp = NULL;
1583 break;
1584 }
1585 }
1586 }
1587 }
1588 if (disp == NULL) {
1589 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1590 // redraw after transform hint changes. See bug 8508397.
1591
1592 // could be null when this layer is using a layerStack
1593 // that is not visible on any display. Also can occur at
1594 // screen off/on times.
1595 disp = getDefaultDisplayDevice();
1596 }
1597 layer->updateTransformHint(disp);
1598 }
1599 }
1600
1601
1602 /*
1603 * Perform our own transaction if needed
1604 */
1605
1606 const LayerVector& layers(mDrawingState.layersSortedByZ);
1607 if (currentLayers.size() > layers.size()) {
1608 // layers have been added
1609 mVisibleRegionsDirty = true;
1610 }
1611
1612 // some layers might have been removed, so
1613 // we need to update the regions they're exposing.
1614 if (mLayersRemoved) {
1615 mLayersRemoved = false;
1616 mVisibleRegionsDirty = true;
1617 const size_t count = layers.size();
1618 for (size_t i=0 ; i<count ; i++) {
1619 const sp<Layer>& layer(layers[i]);
1620 if (currentLayers.indexOf(layer) < 0) {
1621 // this layer is not visible anymore
1622 // TODO: we could traverse the tree from front to back and
1623 // compute the actual visible region
1624 // TODO: we could cache the transformed region
1625 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001626 Region visibleReg = s.active.transform.transform(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 Region(Rect(s.active.w, s.active.h)));
1628 invalidateLayerStack(s.layerStack, visibleReg);
1629 }
1630 }
1631 }
1632
1633 commitTransaction();
1634
1635 updateCursorAsync();
1636}
1637
1638void SurfaceFlinger::updateCursorAsync()
1639{
1640 HWComposer& hwc(getHwComposer());
1641 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1642 sp<const DisplayDevice> hw(mDisplays[dpy]);
1643 const int32_t id = hw->getHwcDisplayId();
1644 if (id < 0) {
1645 continue;
1646 }
1647 const Vector< sp<Layer> >& currentLayers(
1648 hw->getVisibleLayersSortedByZ());
1649 const size_t count = currentLayers.size();
1650 HWComposer::LayerListIterator cur = hwc.begin(id);
1651 const HWComposer::LayerListIterator end = hwc.end(id);
1652 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1653 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1654 continue;
1655 }
1656 const sp<Layer>& layer(currentLayers[i]);
1657 Rect cursorPos = layer->getPosition(hw);
1658 hwc.setCursorPositionAsync(id, cursorPos);
1659 break;
1660 }
1661 }
1662}
1663
1664void SurfaceFlinger::commitTransaction()
1665{
1666 if (!mLayersPendingRemoval.isEmpty()) {
1667 // Notify removed layers now that they can't be drawn from
1668 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1669 mLayersPendingRemoval[i]->onRemoved();
1670 }
1671 mLayersPendingRemoval.clear();
1672 }
1673
1674 // If this transaction is part of a window animation then the next frame
1675 // we composite should be considered an animation as well.
1676 mAnimCompositionPending = mAnimTransactionPending;
1677
1678 mDrawingState = mCurrentState;
1679 mTransactionPending = false;
1680 mAnimTransactionPending = false;
1681 mTransactionCV.broadcast();
1682}
1683
1684void SurfaceFlinger::computeVisibleRegions(
1685 const LayerVector& currentLayers, uint32_t layerStack,
1686 Region& outDirtyRegion, Region& outOpaqueRegion)
1687{
1688 ATRACE_CALL();
1689
1690 Region aboveOpaqueLayers;
1691 Region aboveCoveredLayers;
1692 Region dirty;
1693
1694 outDirtyRegion.clear();
1695
1696 size_t i = currentLayers.size();
1697 while (i--) {
1698 const sp<Layer>& layer = currentLayers[i];
1699
1700 // start with the whole surface at its current location
1701 const Layer::State& s(layer->getDrawingState());
1702
1703 // only consider the layers on the given layer stack
1704 if (s.layerStack != layerStack)
1705 continue;
1706
1707 /*
1708 * opaqueRegion: area of a surface that is fully opaque.
1709 */
1710 Region opaqueRegion;
1711
1712 /*
1713 * visibleRegion: area of a surface that is visible on screen
1714 * and not fully transparent. This is essentially the layer's
1715 * footprint minus the opaque regions above it.
1716 * Areas covered by a translucent surface are considered visible.
1717 */
1718 Region visibleRegion;
1719
1720 /*
1721 * coveredRegion: area of a surface that is covered by all
1722 * visible regions above it (which includes the translucent areas).
1723 */
1724 Region coveredRegion;
1725
1726 /*
1727 * transparentRegion: area of a surface that is hinted to be completely
1728 * transparent. This is only used to tell when the layer has no visible
1729 * non-transparent regions and can be removed from the layer list. It
1730 * does not affect the visibleRegion of this layer or any layers
1731 * beneath it. The hint may not be correct if apps don't respect the
1732 * SurfaceView restrictions (which, sadly, some don't).
1733 */
1734 Region transparentRegion;
1735
1736
1737 // handle hidden surfaces by setting the visible region to empty
1738 if (CC_LIKELY(layer->isVisible())) {
1739 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001740 Rect bounds(s.active.transform.transform(layer->computeBounds()));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 visibleRegion.set(bounds);
1742 if (!visibleRegion.isEmpty()) {
1743 // Remove the transparent area from the visible region
1744 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001745 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001746 if (tr.preserveRects()) {
1747 // transform the transparent region
1748 transparentRegion = tr.transform(s.activeTransparentRegion);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001750 // transformation too complex, can't do the
1751 // transparent region optimization.
1752 transparentRegion.clear();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001753 }
1754 }
1755
1756 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001757 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001758 if (s.alpha==255 && !translucent &&
1759 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1760 // the opaque region is the layer's footprint
1761 opaqueRegion = visibleRegion;
1762 }
1763 }
1764 }
1765
1766 // Clip the covered region to the visible region
1767 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1768
1769 // Update aboveCoveredLayers for next (lower) layer
1770 aboveCoveredLayers.orSelf(visibleRegion);
1771
1772 // subtract the opaque region covered by the layers above us
1773 visibleRegion.subtractSelf(aboveOpaqueLayers);
1774
1775 // compute this layer's dirty region
1776 if (layer->contentDirty) {
1777 // we need to invalidate the whole region
1778 dirty = visibleRegion;
1779 // as well, as the old visible region
1780 dirty.orSelf(layer->visibleRegion);
1781 layer->contentDirty = false;
1782 } else {
1783 /* compute the exposed region:
1784 * the exposed region consists of two components:
1785 * 1) what's VISIBLE now and was COVERED before
1786 * 2) what's EXPOSED now less what was EXPOSED before
1787 *
1788 * note that (1) is conservative, we start with the whole
1789 * visible region but only keep what used to be covered by
1790 * something -- which mean it may have been exposed.
1791 *
1792 * (2) handles areas that were not covered by anything but got
1793 * exposed because of a resize.
1794 */
1795 const Region newExposed = visibleRegion - coveredRegion;
1796 const Region oldVisibleRegion = layer->visibleRegion;
1797 const Region oldCoveredRegion = layer->coveredRegion;
1798 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1799 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1800 }
1801 dirty.subtractSelf(aboveOpaqueLayers);
1802
1803 // accumulate to the screen dirty region
1804 outDirtyRegion.orSelf(dirty);
1805
1806 // Update aboveOpaqueLayers for next (lower) layer
1807 aboveOpaqueLayers.orSelf(opaqueRegion);
1808
1809 // Store the visible region in screen space
1810 layer->setVisibleRegion(visibleRegion);
1811 layer->setCoveredRegion(coveredRegion);
1812 layer->setVisibleNonTransparentRegion(
1813 visibleRegion.subtract(transparentRegion));
1814 }
1815
1816 outOpaqueRegion = aboveOpaqueLayers;
1817}
1818
1819void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1820 const Region& dirty) {
1821 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1822 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1823 if (hw->getLayerStack() == layerStack) {
1824 hw->dirtyRegion.orSelf(dirty);
1825 }
1826 }
1827}
1828
1829bool SurfaceFlinger::handlePageFlip()
1830{
1831 Region dirtyRegion;
1832
1833 bool visibleRegions = false;
1834 const LayerVector& layers(mDrawingState.layersSortedByZ);
1835 bool frameQueued = false;
1836
1837 // Store the set of layers that need updates. This set must not change as
1838 // buffers are being latched, as this could result in a deadlock.
1839 // Example: Two producers share the same command stream and:
1840 // 1.) Layer 0 is latched
1841 // 2.) Layer 0 gets a new frame
1842 // 2.) Layer 1 gets a new frame
1843 // 3.) Layer 1 is latched.
1844 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1845 // second frame. But layer 0's second frame could be waiting on display.
1846 Vector<Layer*> layersWithQueuedFrames;
1847 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1848 const sp<Layer>& layer(layers[i]);
1849 if (layer->hasQueuedFrame()) {
1850 frameQueued = true;
1851 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1852 layersWithQueuedFrames.push_back(layer.get());
1853 } else {
1854 layer->useEmptyDamage();
1855 }
1856 } else {
1857 layer->useEmptyDamage();
1858 }
1859 }
1860 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1861 Layer* layer = layersWithQueuedFrames[i];
1862 const Region dirty(layer->latchBuffer(visibleRegions));
1863 layer->useSurfaceDamage();
1864 const Layer::State& s(layer->getDrawingState());
1865 invalidateLayerStack(s.layerStack, dirty);
1866 }
1867
1868 mVisibleRegionsDirty |= visibleRegions;
1869
1870 // If we will need to wake up at some time in the future to deal with a
1871 // queued frame that shouldn't be displayed during this vsync period, wake
1872 // up during the next vsync period to check again.
1873 if (frameQueued && layersWithQueuedFrames.empty()) {
1874 signalLayerUpdate();
1875 }
1876
1877 // Only continue with the refresh if there is actually new work to do
1878 return !layersWithQueuedFrames.empty();
1879}
1880
1881void SurfaceFlinger::invalidateHwcGeometry()
1882{
1883 mHwWorkListDirty = true;
1884}
1885
1886
1887void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1888 const Region& inDirtyRegion)
1889{
1890 // We only need to actually compose the display if:
1891 // 1) It is being handled by hardware composer, which may need this to
1892 // keep its virtual display state machine in sync, or
1893 // 2) There is work to be done (the dirty region isn't empty)
1894 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1895 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1896 return;
1897 }
1898
1899 Region dirtyRegion(inDirtyRegion);
1900
1901 // compute the invalid region
1902 hw->swapRegion.orSelf(dirtyRegion);
1903
1904 uint32_t flags = hw->getFlags();
1905 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1906 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1907 // takes a rectangle, we must make sure to update that whole
1908 // rectangle in that case
1909 dirtyRegion.set(hw->swapRegion.bounds());
1910 } else {
1911 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1912 // We need to redraw the rectangle that will be updated
1913 // (pushed to the framebuffer).
1914 // This is needed because PARTIAL_UPDATES only takes one
1915 // rectangle instead of a region (see DisplayDevice::flip())
1916 dirtyRegion.set(hw->swapRegion.bounds());
1917 } else {
1918 // we need to redraw everything (the whole screen)
1919 dirtyRegion.set(hw->bounds());
1920 hw->swapRegion = dirtyRegion;
1921 }
1922 }
1923
1924 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1925 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1926 } else {
1927 RenderEngine& engine(getRenderEngine());
1928 mat4 colorMatrix = mColorMatrix;
1929 if (mDaltonize) {
1930 colorMatrix = colorMatrix * mDaltonizer();
1931 }
1932 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1933 doComposeSurfaces(hw, dirtyRegion);
1934 engine.setupColorTransform(oldMatrix);
1935 }
1936
1937 // update the swap region and clear the dirty region
1938 hw->swapRegion.orSelf(dirtyRegion);
1939
1940 // swap buffers (presentation)
1941 hw->swapBuffers(getHwComposer());
1942}
1943
1944bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1945{
1946 RenderEngine& engine(getRenderEngine());
1947 const int32_t id = hw->getHwcDisplayId();
1948 HWComposer& hwc(getHwComposer());
1949 HWComposer::LayerListIterator cur = hwc.begin(id);
1950 const HWComposer::LayerListIterator end = hwc.end(id);
1951
1952 bool hasGlesComposition = hwc.hasGlesComposition(id);
1953 if (hasGlesComposition) {
1954 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1955 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1956 hw->getDisplayName().string());
1957 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1958 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1959 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1960 }
1961 return false;
1962 }
1963
1964 // Never touch the framebuffer if we don't have any framebuffer layers
1965 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1966 if (hasHwcComposition) {
1967 // when using overlays, we assume a fully transparent framebuffer
1968 // NOTE: we could reduce how much we need to clear, for instance
1969 // remove where there are opaque FB layers. however, on some
1970 // GPUs doing a "clean slate" clear might be more efficient.
1971 // We'll revisit later if needed.
1972 engine.clearWithColor(0, 0, 0, 0);
1973 } else {
1974 // we start with the whole screen area
1975 const Region bounds(hw->getBounds());
1976
1977 // we remove the scissor part
1978 // we're left with the letterbox region
1979 // (common case is that letterbox ends-up being empty)
1980 const Region letterbox(bounds.subtract(hw->getScissor()));
1981
1982 // compute the area to clear
1983 Region region(hw->undefinedRegion.merge(letterbox));
1984
1985 // but limit it to the dirty region
1986 region.andSelf(dirty);
1987
1988 // screen is already cleared here
1989 if (!region.isEmpty()) {
1990 // can happen with SurfaceView
1991 drawWormhole(hw, region);
1992 }
1993 }
1994
1995 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1996 // just to be on the safe side, we don't set the
1997 // scissor on the main display. It should never be needed
1998 // anyways (though in theory it could since the API allows it).
1999 const Rect& bounds(hw->getBounds());
2000 const Rect& scissor(hw->getScissor());
2001 if (scissor != bounds) {
2002 // scissor doesn't match the screen's dimensions, so we
2003 // need to clear everything outside of it and enable
2004 // the GL scissor so we don't draw anything where we shouldn't
2005
2006 // enable scissor for this frame
2007 const uint32_t height = hw->getHeight();
2008 engine.setScissor(scissor.left, height - scissor.bottom,
2009 scissor.getWidth(), scissor.getHeight());
2010 }
2011 }
2012 }
2013
2014 /*
2015 * and then, render the layers targeted at the framebuffer
2016 */
2017
2018 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2019 const size_t count = layers.size();
2020 const Transform& tr = hw->getTransform();
2021 if (cur != end) {
2022 // we're using h/w composer
2023 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2024 const sp<Layer>& layer(layers[i]);
2025 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2026 if (!clip.isEmpty()) {
2027 switch (cur->getCompositionType()) {
2028 case HWC_CURSOR_OVERLAY:
2029 case HWC_OVERLAY: {
2030 const Layer::State& state(layer->getDrawingState());
2031 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2032 && i
2033 && layer->isOpaque(state) && (state.alpha == 0xFF)
2034 && hasGlesComposition) {
2035 // never clear the very first layer since we're
2036 // guaranteed the FB is already cleared
2037 layer->clearWithOpenGL(hw, clip);
2038 }
2039 break;
2040 }
2041 case HWC_FRAMEBUFFER: {
2042 layer->draw(hw, clip);
2043 break;
2044 }
2045 case HWC_FRAMEBUFFER_TARGET: {
2046 // this should not happen as the iterator shouldn't
2047 // let us get there.
2048 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2049 break;
2050 }
2051 }
2052 }
2053 layer->setAcquireFence(hw, *cur);
2054 }
2055 } else {
2056 // we're not using h/w composer
2057 for (size_t i=0 ; i<count ; ++i) {
2058 const sp<Layer>& layer(layers[i]);
2059 const Region clip(dirty.intersect(
2060 tr.transform(layer->visibleRegion)));
2061 if (!clip.isEmpty()) {
2062 layer->draw(hw, clip);
2063 }
2064 }
2065 }
2066
2067 // disable scissor at the end of the frame
2068 engine.disableScissor();
2069 return true;
2070}
2071
2072void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2073 const int32_t height = hw->getHeight();
2074 RenderEngine& engine(getRenderEngine());
2075 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2076}
2077
2078status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2079 const sp<IBinder>& handle,
2080 const sp<IGraphicBufferProducer>& gbc,
2081 const sp<Layer>& lbc)
2082{
2083 // add this layer to the current state list
2084 {
2085 Mutex::Autolock _l(mStateLock);
2086 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2087 return NO_MEMORY;
2088 }
2089 mCurrentState.layersSortedByZ.add(lbc);
2090 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2091 }
2092
2093 // attach this layer to the client
2094 client->attachLayer(handle, lbc);
2095
2096 return NO_ERROR;
2097}
2098
Dan Stozade84eb62016-08-09 13:21:03 -07002099status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 Mutex::Autolock _l(mStateLock);
Dan Stozade84eb62016-08-09 13:21:03 -07002101 sp<Layer> layer = weakLayer.promote();
2102 if (layer == nullptr) {
2103 // The layer has already been removed, carry on
2104 return NO_ERROR;
2105 }
2106
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2108 if (index >= 0) {
2109 mLayersPendingRemoval.push(layer);
2110 mLayersRemoved = true;
2111 setTransactionFlags(eTransactionNeeded);
2112 return NO_ERROR;
2113 }
2114 return status_t(index);
2115}
2116
2117uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2118 return android_atomic_release_load(&mTransactionFlags);
2119}
2120
2121uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2122 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2123}
2124
2125uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2126 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2127 if ((old & flags)==0) { // wake the server up
2128 signalTransaction();
2129 }
2130 return old;
2131}
2132
2133void SurfaceFlinger::setTransactionState(
2134 const Vector<ComposerState>& state,
2135 const Vector<DisplayState>& displays,
2136 uint32_t flags)
2137{
2138 ATRACE_CALL();
2139 Mutex::Autolock _l(mStateLock);
2140 uint32_t transactionFlags = 0;
2141
2142 if (flags & eAnimation) {
2143 // For window updates that are part of an animation we must wait for
2144 // previous animation "frames" to be handled.
2145 while (mAnimTransactionPending) {
2146 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2147 if (CC_UNLIKELY(err != NO_ERROR)) {
2148 // just in case something goes wrong in SF, return to the
2149 // caller after a few seconds.
2150 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2151 "waiting for previous animation frame");
2152 mAnimTransactionPending = false;
2153 break;
2154 }
2155 }
2156 }
2157
2158 size_t count = displays.size();
2159 for (size_t i=0 ; i<count ; i++) {
2160 const DisplayState& s(displays[i]);
2161 transactionFlags |= setDisplayStateLocked(s);
2162 }
2163
2164 count = state.size();
2165 for (size_t i=0 ; i<count ; i++) {
2166 const ComposerState& s(state[i]);
2167 // Here we need to check that the interface we're given is indeed
2168 // one of our own. A malicious client could give us a NULL
2169 // IInterface, or one of its own or even one of our own but a
2170 // different type. All these situations would cause us to crash.
2171 //
2172 // NOTE: it would be better to use RTTI as we could directly check
2173 // that we have a Client*. however, RTTI is disabled in Android.
2174 if (s.client != NULL) {
2175 sp<IBinder> binder = IInterface::asBinder(s.client);
2176 if (binder != NULL) {
2177 String16 desc(binder->getInterfaceDescriptor());
2178 if (desc == ISurfaceComposerClient::descriptor) {
2179 sp<Client> client( static_cast<Client *>(s.client.get()) );
2180 transactionFlags |= setClientStateLocked(client, s.state);
2181 }
2182 }
2183 }
2184 }
2185
Robert Carr2a7dbb42016-05-24 11:41:28 -07002186 // If a synchronous transaction is explicitly requested without any changes,
2187 // force a transaction anyway. This can be used as a flush mechanism for
2188 // previous async transactions.
2189 if (transactionFlags == 0 && (flags & eSynchronous)) {
2190 transactionFlags = eTransactionNeeded;
2191 }
2192
Dan Stoza9e56aa02015-11-02 13:00:03 -08002193 if (transactionFlags) {
2194 // this triggers the transaction
2195 setTransactionFlags(transactionFlags);
2196
2197 // if this is a synchronous transaction, wait for it to take effect
2198 // before returning.
2199 if (flags & eSynchronous) {
2200 mTransactionPending = true;
2201 }
2202 if (flags & eAnimation) {
2203 mAnimTransactionPending = true;
2204 }
2205 while (mTransactionPending) {
2206 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2207 if (CC_UNLIKELY(err != NO_ERROR)) {
2208 // just in case something goes wrong in SF, return to the
2209 // called after a few seconds.
2210 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2211 mTransactionPending = false;
2212 break;
2213 }
2214 }
2215 }
2216}
2217
2218uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2219{
2220 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2221 if (dpyIdx < 0)
2222 return 0;
2223
2224 uint32_t flags = 0;
2225 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2226 if (disp.isValid()) {
2227 const uint32_t what = s.what;
2228 if (what & DisplayState::eSurfaceChanged) {
2229 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2230 disp.surface = s.surface;
2231 flags |= eDisplayTransactionNeeded;
2232 }
2233 }
2234 if (what & DisplayState::eLayerStackChanged) {
2235 if (disp.layerStack != s.layerStack) {
2236 disp.layerStack = s.layerStack;
2237 flags |= eDisplayTransactionNeeded;
2238 }
2239 }
2240 if (what & DisplayState::eDisplayProjectionChanged) {
2241 if (disp.orientation != s.orientation) {
2242 disp.orientation = s.orientation;
2243 flags |= eDisplayTransactionNeeded;
2244 }
2245 if (disp.frame != s.frame) {
2246 disp.frame = s.frame;
2247 flags |= eDisplayTransactionNeeded;
2248 }
2249 if (disp.viewport != s.viewport) {
2250 disp.viewport = s.viewport;
2251 flags |= eDisplayTransactionNeeded;
2252 }
2253 }
2254 if (what & DisplayState::eDisplaySizeChanged) {
2255 if (disp.width != s.width) {
2256 disp.width = s.width;
2257 flags |= eDisplayTransactionNeeded;
2258 }
2259 if (disp.height != s.height) {
2260 disp.height = s.height;
2261 flags |= eDisplayTransactionNeeded;
2262 }
2263 }
2264 }
2265 return flags;
2266}
2267
2268uint32_t SurfaceFlinger::setClientStateLocked(
2269 const sp<Client>& client,
2270 const layer_state_t& s)
2271{
2272 uint32_t flags = 0;
2273 sp<Layer> layer(client->getLayerUser(s.surface));
2274 if (layer != 0) {
2275 const uint32_t what = s.what;
Robert Carr82364e32016-05-15 11:27:47 -07002276 bool positionAppliesWithResize =
2277 what & layer_state_t::ePositionAppliesWithResize;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 if (what & layer_state_t::ePositionChanged) {
Robert Carr82364e32016-05-15 11:27:47 -07002279 if (layer->setPosition(s.x, s.y, !positionAppliesWithResize)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002280 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002281 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002282 }
2283 if (what & layer_state_t::eLayerChanged) {
2284 // NOTE: index needs to be calculated before we update the state
2285 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2286 if (layer->setLayer(s.z) && idx >= 0) {
2287 mCurrentState.layersSortedByZ.removeAt(idx);
2288 mCurrentState.layersSortedByZ.add(layer);
2289 // we need traversal (state changed)
2290 // AND transaction (list changed)
2291 flags |= eTransactionNeeded|eTraversalNeeded;
2292 }
2293 }
2294 if (what & layer_state_t::eSizeChanged) {
2295 if (layer->setSize(s.w, s.h)) {
2296 flags |= eTraversalNeeded;
2297 }
2298 }
2299 if (what & layer_state_t::eAlphaChanged) {
2300 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2301 flags |= eTraversalNeeded;
2302 }
2303 if (what & layer_state_t::eMatrixChanged) {
2304 if (layer->setMatrix(s.matrix))
2305 flags |= eTraversalNeeded;
2306 }
2307 if (what & layer_state_t::eTransparentRegionChanged) {
2308 if (layer->setTransparentRegionHint(s.transparentRegion))
2309 flags |= eTraversalNeeded;
2310 }
2311 if (what & layer_state_t::eFlagsChanged) {
2312 if (layer->setFlags(s.flags, s.mask))
2313 flags |= eTraversalNeeded;
2314 }
2315 if (what & layer_state_t::eCropChanged) {
2316 if (layer->setCrop(s.crop))
2317 flags |= eTraversalNeeded;
2318 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002319 if (what & layer_state_t::eFinalCropChanged) {
2320 if (layer->setFinalCrop(s.finalCrop))
2321 flags |= eTraversalNeeded;
2322 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002323 if (what & layer_state_t::eLayerStackChanged) {
2324 // NOTE: index needs to be calculated before we update the state
2325 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2326 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2327 mCurrentState.layersSortedByZ.removeAt(idx);
2328 mCurrentState.layersSortedByZ.add(layer);
2329 // we need traversal (state changed)
2330 // AND transaction (list changed)
2331 flags |= eTransactionNeeded|eTraversalNeeded;
2332 }
2333 }
2334 if (what & layer_state_t::eDeferTransaction) {
2335 layer->deferTransactionUntil(s.handle, s.frameNumber);
2336 // We don't trigger a traversal here because if no other state is
2337 // changed, we don't want this to cause any more work
2338 }
Robert Carrc3574f72016-03-24 12:19:32 -07002339 if (what & layer_state_t::eOverrideScalingModeChanged) {
2340 layer->setOverrideScalingMode(s.overrideScalingMode);
2341 // We don't trigger a traversal here because if no other state is
2342 // changed, we don't want this to cause any more work
2343 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002344 }
2345 return flags;
2346}
2347
2348status_t SurfaceFlinger::createLayer(
2349 const String8& name,
2350 const sp<Client>& client,
2351 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2352 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2353{
2354 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2355 if (int32_t(w|h) < 0) {
2356 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2357 int(w), int(h));
2358 return BAD_VALUE;
2359 }
2360
2361 status_t result = NO_ERROR;
2362
2363 sp<Layer> layer;
2364
2365 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2366 case ISurfaceComposerClient::eFXSurfaceNormal:
2367 result = createNormalLayer(client,
2368 name, w, h, flags, format,
2369 handle, gbp, &layer);
2370 break;
2371 case ISurfaceComposerClient::eFXSurfaceDim:
2372 result = createDimLayer(client,
2373 name, w, h, flags,
2374 handle, gbp, &layer);
2375 break;
2376 default:
2377 result = BAD_VALUE;
2378 break;
2379 }
2380
2381 if (result != NO_ERROR) {
2382 return result;
2383 }
2384
2385 result = addClientLayer(client, *handle, *gbp, layer);
2386 if (result != NO_ERROR) {
2387 return result;
2388 }
2389
2390 setTransactionFlags(eTransactionNeeded);
2391 return result;
2392}
2393
2394status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2395 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2396 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2397{
2398 // initialize the surfaces
2399 switch (format) {
2400 case PIXEL_FORMAT_TRANSPARENT:
2401 case PIXEL_FORMAT_TRANSLUCENT:
2402 format = PIXEL_FORMAT_RGBA_8888;
2403 break;
2404 case PIXEL_FORMAT_OPAQUE:
2405 format = PIXEL_FORMAT_RGBX_8888;
2406 break;
2407 }
2408
2409 *outLayer = new Layer(this, client, name, w, h, flags);
2410 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2411 if (err == NO_ERROR) {
2412 *handle = (*outLayer)->getHandle();
2413 *gbp = (*outLayer)->getProducer();
2414 }
2415
2416 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2417 return err;
2418}
2419
2420status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2421 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2422 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2423{
2424 *outLayer = new LayerDim(this, client, name, w, h, flags);
2425 *handle = (*outLayer)->getHandle();
2426 *gbp = (*outLayer)->getProducer();
2427 return NO_ERROR;
2428}
2429
2430status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2431{
2432 // called by the window manager when it wants to remove a Layer
2433 status_t err = NO_ERROR;
2434 sp<Layer> l(client->getLayerUser(handle));
2435 if (l != NULL) {
2436 err = removeLayer(l);
2437 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2438 "error removing layer=%p (%s)", l.get(), strerror(-err));
2439 }
2440 return err;
2441}
2442
2443status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2444{
2445 // called by ~LayerCleaner() when all references to the IBinder (handle)
2446 // are gone
Dan Stozade84eb62016-08-09 13:21:03 -07002447 return removeLayer(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448}
2449
2450// ---------------------------------------------------------------------------
2451
2452void SurfaceFlinger::onInitializeDisplays() {
2453 // reset screen orientation and use primary layer stack
2454 Vector<ComposerState> state;
2455 Vector<DisplayState> displays;
2456 DisplayState d;
2457 d.what = DisplayState::eDisplayProjectionChanged |
2458 DisplayState::eLayerStackChanged;
2459 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2460 d.layerStack = 0;
2461 d.orientation = DisplayState::eOrientationDefault;
2462 d.frame.makeInvalid();
2463 d.viewport.makeInvalid();
2464 d.width = 0;
2465 d.height = 0;
2466 displays.add(d);
2467 setTransactionState(state, displays, 0);
2468 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2469
2470 const nsecs_t period =
2471 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2472 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2473}
2474
2475void SurfaceFlinger::initializeDisplays() {
2476 class MessageScreenInitialized : public MessageBase {
2477 SurfaceFlinger* flinger;
2478 public:
2479 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2480 virtual bool handler() {
2481 flinger->onInitializeDisplays();
2482 return true;
2483 }
2484 };
2485 sp<MessageBase> msg = new MessageScreenInitialized(this);
2486 postMessageAsync(msg); // we may be called from main thread, use async message
2487}
2488
2489void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2490 int mode) {
2491 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2492 this);
2493 int32_t type = hw->getDisplayType();
2494 int currentMode = hw->getPowerMode();
2495
2496 if (mode == currentMode) {
2497 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2498 return;
2499 }
2500
2501 hw->setPowerMode(mode);
2502 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2503 ALOGW("Trying to set power mode for virtual display");
2504 return;
2505 }
2506
2507 if (currentMode == HWC_POWER_MODE_OFF) {
2508 getHwComposer().setPowerMode(type, mode);
2509 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2510 // FIXME: eventthread only knows about the main display right now
2511 mEventThread->onScreenAcquired();
2512 resyncToHardwareVsync(true);
2513 }
2514
2515 mVisibleRegionsDirty = true;
2516 mHasPoweredOff = true;
2517 repaintEverything();
2518 } else if (mode == HWC_POWER_MODE_OFF) {
2519 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2520 disableHardwareVsync(true); // also cancels any in-progress resync
2521
2522 // FIXME: eventthread only knows about the main display right now
2523 mEventThread->onScreenReleased();
2524 }
2525
2526 getHwComposer().setPowerMode(type, mode);
2527 mVisibleRegionsDirty = true;
2528 // from this point on, SF will stop drawing on this display
2529 } else {
2530 getHwComposer().setPowerMode(type, mode);
2531 }
2532}
2533
2534void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2535 class MessageSetPowerMode: public MessageBase {
2536 SurfaceFlinger& mFlinger;
2537 sp<IBinder> mDisplay;
2538 int mMode;
2539 public:
2540 MessageSetPowerMode(SurfaceFlinger& flinger,
2541 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2542 mDisplay(disp) { mMode = mode; }
2543 virtual bool handler() {
2544 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2545 if (hw == NULL) {
2546 ALOGE("Attempt to set power mode = %d for null display %p",
2547 mMode, mDisplay.get());
2548 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2549 ALOGW("Attempt to set power mode = %d for virtual display",
2550 mMode);
2551 } else {
2552 mFlinger.setPowerModeInternal(hw, mMode);
2553 }
2554 return true;
2555 }
2556 };
2557 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2558 postMessageSync(msg);
2559}
2560
2561// ---------------------------------------------------------------------------
2562
2563status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2564{
2565 String8 result;
2566
2567 IPCThreadState* ipc = IPCThreadState::self();
2568 const int pid = ipc->getCallingPid();
2569 const int uid = ipc->getCallingUid();
2570 if ((uid != AID_SHELL) &&
2571 !PermissionCache::checkPermission(sDump, pid, uid)) {
2572 result.appendFormat("Permission Denial: "
2573 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2574 } else {
2575 // Try to get the main lock, but give up after one second
2576 // (this would indicate SF is stuck, but we want to be able to
2577 // print something in dumpsys).
2578 status_t err = mStateLock.timedLock(s2ns(1));
2579 bool locked = (err == NO_ERROR);
2580 if (!locked) {
2581 result.appendFormat(
2582 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2583 "dumping anyways (no locks held)\n", strerror(-err), err);
2584 }
2585
2586 bool dumpAll = true;
2587 size_t index = 0;
2588 size_t numArgs = args.size();
2589 if (numArgs) {
2590 if ((index < numArgs) &&
2591 (args[index] == String16("--list"))) {
2592 index++;
2593 listLayersLocked(args, index, result);
2594 dumpAll = false;
2595 }
2596
2597 if ((index < numArgs) &&
2598 (args[index] == String16("--latency"))) {
2599 index++;
2600 dumpStatsLocked(args, index, result);
2601 dumpAll = false;
2602 }
2603
2604 if ((index < numArgs) &&
2605 (args[index] == String16("--latency-clear"))) {
2606 index++;
2607 clearStatsLocked(args, index, result);
2608 dumpAll = false;
2609 }
2610
2611 if ((index < numArgs) &&
2612 (args[index] == String16("--dispsync"))) {
2613 index++;
2614 mPrimaryDispSync.dump(result);
2615 dumpAll = false;
2616 }
2617
2618 if ((index < numArgs) &&
2619 (args[index] == String16("--static-screen"))) {
2620 index++;
2621 dumpStaticScreenStats(result);
2622 dumpAll = false;
2623 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002624
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002625#ifdef ENABLE_FENCE_TRACKING
Pablo Ceballos40845df2016-01-25 17:41:15 -08002626 if ((index < numArgs) &&
2627 (args[index] == String16("--fences"))) {
2628 index++;
2629 mFenceTracker.dump(&result);
2630 dumpAll = false;
2631 }
Pablo Ceballos69a1a382016-03-30 15:28:05 -07002632#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 }
2634
2635 if (dumpAll) {
2636 dumpAllLocked(args, index, result);
2637 }
2638
2639 if (locked) {
2640 mStateLock.unlock();
2641 }
2642 }
2643 write(fd, result.string(), result.size());
2644 return NO_ERROR;
2645}
2646
2647void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2648 size_t& /* index */, String8& result) const
2649{
2650 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2651 const size_t count = currentLayers.size();
2652 for (size_t i=0 ; i<count ; i++) {
2653 const sp<Layer>& layer(currentLayers[i]);
2654 result.appendFormat("%s\n", layer->getName().string());
2655 }
2656}
2657
2658void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2659 String8& result) const
2660{
2661 String8 name;
2662 if (index < args.size()) {
2663 name = String8(args[index]);
2664 index++;
2665 }
2666
2667 const nsecs_t period =
2668 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2669 result.appendFormat("%" PRId64 "\n", period);
2670
2671 if (name.isEmpty()) {
2672 mAnimFrameTracker.dumpStats(result);
2673 } else {
2674 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2675 const size_t count = currentLayers.size();
2676 for (size_t i=0 ; i<count ; i++) {
2677 const sp<Layer>& layer(currentLayers[i]);
2678 if (name == layer->getName()) {
2679 layer->dumpFrameStats(result);
2680 }
2681 }
2682 }
2683}
2684
2685void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2686 String8& /* result */)
2687{
2688 String8 name;
2689 if (index < args.size()) {
2690 name = String8(args[index]);
2691 index++;
2692 }
2693
2694 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2695 const size_t count = currentLayers.size();
2696 for (size_t i=0 ; i<count ; i++) {
2697 const sp<Layer>& layer(currentLayers[i]);
2698 if (name.isEmpty() || (name == layer->getName())) {
2699 layer->clearFrameStats();
2700 }
2701 }
2702
2703 mAnimFrameTracker.clearStats();
2704}
2705
2706// This should only be called from the main thread. Otherwise it would need
2707// the lock and should use mCurrentState rather than mDrawingState.
2708void SurfaceFlinger::logFrameStats() {
2709 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2710 const size_t count = drawingLayers.size();
2711 for (size_t i=0 ; i<count ; i++) {
2712 const sp<Layer>& layer(drawingLayers[i]);
2713 layer->logFrameStats();
2714 }
2715
2716 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2717}
2718
2719/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2720{
2721 static const char* config =
2722 " [sf"
2723#ifdef HAS_CONTEXT_PRIORITY
2724 " HAS_CONTEXT_PRIORITY"
2725#endif
2726#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2727 " NEVER_DEFAULT_TO_ASYNC_MODE"
2728#endif
2729#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2730 " TARGET_DISABLE_TRIPLE_BUFFERING"
2731#endif
2732 "]";
2733 result.append(config);
2734}
2735
2736void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2737{
2738 result.appendFormat("Static screen stats:\n");
2739 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2740 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2741 float percent = 100.0f *
2742 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2743 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2744 b + 1, bucketTimeSec, percent);
2745 }
2746 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2747 float percent = 100.0f *
2748 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2749 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2750 NUM_BUCKETS - 1, bucketTimeSec, percent);
2751}
2752
2753void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2754 String8& result) const
2755{
2756 bool colorize = false;
2757 if (index < args.size()
2758 && (args[index] == String16("--color"))) {
2759 colorize = true;
2760 index++;
2761 }
2762
2763 Colorizer colorizer(colorize);
2764
2765 // figure out if we're stuck somewhere
2766 const nsecs_t now = systemTime();
2767 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2768 const nsecs_t inTransaction(mDebugInTransaction);
2769 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2770 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2771
2772 /*
2773 * Dump library configuration.
2774 */
2775
2776 colorizer.bold(result);
2777 result.append("Build configuration:");
2778 colorizer.reset(result);
2779 appendSfConfigString(result);
2780 appendUiConfigString(result);
2781 appendGuiConfigString(result);
2782 result.append("\n");
2783
2784 colorizer.bold(result);
2785 result.append("Sync configuration: ");
2786 colorizer.reset(result);
2787 result.append(SyncFeatures::getInstance().toString());
2788 result.append("\n");
2789
2790 colorizer.bold(result);
2791 result.append("DispSync configuration: ");
2792 colorizer.reset(result);
2793 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2794 "present offset %d ns (refresh %" PRId64 " ns)",
2795 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2796 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2797 result.append("\n");
2798
2799 // Dump static screen stats
2800 result.append("\n");
2801 dumpStaticScreenStats(result);
2802 result.append("\n");
2803
2804 /*
2805 * Dump the visible layer list
2806 */
2807 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2808 const size_t count = currentLayers.size();
2809 colorizer.bold(result);
2810 result.appendFormat("Visible layers (count = %zu)\n", count);
2811 colorizer.reset(result);
2812 for (size_t i=0 ; i<count ; i++) {
2813 const sp<Layer>& layer(currentLayers[i]);
2814 layer->dump(result, colorizer);
2815 }
2816
2817 /*
2818 * Dump Display state
2819 */
2820
2821 colorizer.bold(result);
2822 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2823 colorizer.reset(result);
2824 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2825 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2826 hw->dump(result);
2827 }
2828
2829 /*
2830 * Dump SurfaceFlinger global state
2831 */
2832
2833 colorizer.bold(result);
2834 result.append("SurfaceFlinger global state:\n");
2835 colorizer.reset(result);
2836
2837 HWComposer& hwc(getHwComposer());
2838 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2839
2840 colorizer.bold(result);
2841 result.appendFormat("EGL implementation : %s\n",
2842 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2843 colorizer.reset(result);
2844 result.appendFormat("%s\n",
2845 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2846
2847 mRenderEngine->dump(result);
2848
2849 hw->undefinedRegion.dump(result, "undefinedRegion");
2850 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2851 hw->getOrientation(), hw->isDisplayOn());
2852 result.appendFormat(
2853 " last eglSwapBuffers() time: %f us\n"
2854 " last transaction time : %f us\n"
2855 " transaction-flags : %08x\n"
2856 " refresh-rate : %f fps\n"
2857 " x-dpi : %f\n"
2858 " y-dpi : %f\n"
2859 " gpu_to_cpu_unsupported : %d\n"
2860 ,
2861 mLastSwapBufferTime/1000.0,
2862 mLastTransactionTime/1000.0,
2863 mTransactionFlags,
2864 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2865 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2866 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2867 !mGpuToCpuSupported);
2868
2869 result.appendFormat(" eglSwapBuffers time: %f us\n",
2870 inSwapBuffersDuration/1000.0);
2871
2872 result.appendFormat(" transaction time: %f us\n",
2873 inTransactionDuration/1000.0);
2874
2875 /*
2876 * VSYNC state
2877 */
2878 mEventThread->dump(result);
2879
2880 /*
2881 * Dump HWComposer state
2882 */
2883 colorizer.bold(result);
2884 result.append("h/w composer state:\n");
2885 colorizer.reset(result);
2886 result.appendFormat(" h/w composer %s and %s\n",
2887 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2888 (mDebugDisableHWC || mDebugRegion || mDaltonize
2889 || mHasColorMatrix) ? "disabled" : "enabled");
2890 hwc.dump(result);
2891
2892 /*
2893 * Dump gralloc state
2894 */
2895 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2896 alloc.dump(result);
2897}
2898
2899const Vector< sp<Layer> >&
2900SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2901 // Note: mStateLock is held here
2902 wp<IBinder> dpy;
2903 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2904 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2905 dpy = mDisplays.keyAt(i);
2906 break;
2907 }
2908 }
2909 if (dpy == NULL) {
2910 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2911 // Just use the primary display so we have something to return
2912 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2913 }
2914 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2915}
2916
2917bool SurfaceFlinger::startDdmConnection()
2918{
2919 void* libddmconnection_dso =
2920 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2921 if (!libddmconnection_dso) {
2922 return false;
2923 }
2924 void (*DdmConnection_start)(const char* name);
2925 DdmConnection_start =
2926 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2927 if (!DdmConnection_start) {
2928 dlclose(libddmconnection_dso);
2929 return false;
2930 }
2931 (*DdmConnection_start)(getServiceName());
2932 return true;
2933}
2934
2935status_t SurfaceFlinger::onTransact(
2936 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2937{
2938 switch (code) {
2939 case CREATE_CONNECTION:
2940 case CREATE_DISPLAY:
2941 case SET_TRANSACTION_STATE:
2942 case BOOT_FINISHED:
2943 case CLEAR_ANIMATION_FRAME_STATS:
2944 case GET_ANIMATION_FRAME_STATS:
2945 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07002946 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002947 {
2948 // codes that require permission check
2949 IPCThreadState* ipc = IPCThreadState::self();
2950 const int pid = ipc->getCallingPid();
2951 const int uid = ipc->getCallingUid();
2952 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2953 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2954 ALOGE("Permission Denial: "
2955 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2956 return PERMISSION_DENIED;
2957 }
2958 break;
2959 }
2960 case CAPTURE_SCREEN:
2961 {
2962 // codes that require permission check
2963 IPCThreadState* ipc = IPCThreadState::self();
2964 const int pid = ipc->getCallingPid();
2965 const int uid = ipc->getCallingUid();
2966 if ((uid != AID_GRAPHICS) &&
2967 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2968 ALOGE("Permission Denial: "
2969 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2970 return PERMISSION_DENIED;
2971 }
2972 break;
2973 }
2974 }
2975
2976 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2977 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2978 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2979 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2980 IPCThreadState* ipc = IPCThreadState::self();
2981 const int pid = ipc->getCallingPid();
2982 const int uid = ipc->getCallingUid();
2983 ALOGE("Permission Denial: "
2984 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2985 return PERMISSION_DENIED;
2986 }
2987 int n;
2988 switch (code) {
2989 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2990 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2991 return NO_ERROR;
2992 case 1002: // SHOW_UPDATES
2993 n = data.readInt32();
2994 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2995 invalidateHwcGeometry();
2996 repaintEverything();
2997 return NO_ERROR;
2998 case 1004:{ // repaint everything
2999 repaintEverything();
3000 return NO_ERROR;
3001 }
3002 case 1005:{ // force transaction
3003 setTransactionFlags(
3004 eTransactionNeeded|
3005 eDisplayTransactionNeeded|
3006 eTraversalNeeded);
3007 return NO_ERROR;
3008 }
3009 case 1006:{ // send empty update
3010 signalRefresh();
3011 return NO_ERROR;
3012 }
3013 case 1008: // toggle use of hw composer
3014 n = data.readInt32();
3015 mDebugDisableHWC = n ? 1 : 0;
3016 invalidateHwcGeometry();
3017 repaintEverything();
3018 return NO_ERROR;
3019 case 1009: // toggle use of transform hint
3020 n = data.readInt32();
3021 mDebugDisableTransformHint = n ? 1 : 0;
3022 invalidateHwcGeometry();
3023 repaintEverything();
3024 return NO_ERROR;
3025 case 1010: // interrogate.
3026 reply->writeInt32(0);
3027 reply->writeInt32(0);
3028 reply->writeInt32(mDebugRegion);
3029 reply->writeInt32(0);
3030 reply->writeInt32(mDebugDisableHWC);
3031 return NO_ERROR;
3032 case 1013: {
3033 Mutex::Autolock _l(mStateLock);
3034 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3035 reply->writeInt32(hw->getPageFlipCount());
3036 return NO_ERROR;
3037 }
3038 case 1014: {
3039 // daltonize
3040 n = data.readInt32();
3041 switch (n % 10) {
3042 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3043 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3044 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3045 }
3046 if (n >= 10) {
3047 mDaltonizer.setMode(Daltonizer::correction);
3048 } else {
3049 mDaltonizer.setMode(Daltonizer::simulation);
3050 }
3051 mDaltonize = n > 0;
3052 invalidateHwcGeometry();
3053 repaintEverything();
3054 return NO_ERROR;
3055 }
3056 case 1015: {
3057 // apply a color matrix
3058 n = data.readInt32();
3059 mHasColorMatrix = n ? 1 : 0;
3060 if (n) {
3061 // color matrix is sent as mat3 matrix followed by vec3
3062 // offset, then packed into a mat4 where the last row is
3063 // the offset and extra values are 0
3064 for (size_t i = 0 ; i < 4; i++) {
3065 for (size_t j = 0; j < 4; j++) {
3066 mColorMatrix[i][j] = data.readFloat();
3067 }
3068 }
3069 } else {
3070 mColorMatrix = mat4();
3071 }
3072 invalidateHwcGeometry();
3073 repaintEverything();
3074 return NO_ERROR;
3075 }
3076 // This is an experimental interface
3077 // Needs to be shifted to proper binder interface when we productize
3078 case 1016: {
3079 n = data.readInt32();
3080 mPrimaryDispSync.setRefreshSkipCount(n);
3081 return NO_ERROR;
3082 }
3083 case 1017: {
3084 n = data.readInt32();
3085 mForceFullDamage = static_cast<bool>(n);
3086 return NO_ERROR;
3087 }
3088 case 1018: { // Modify Choreographer's phase offset
3089 n = data.readInt32();
3090 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3091 return NO_ERROR;
3092 }
3093 case 1019: { // Modify SurfaceFlinger's phase offset
3094 n = data.readInt32();
3095 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3096 return NO_ERROR;
3097 }
3098 }
3099 }
3100 return err;
3101}
3102
3103void SurfaceFlinger::repaintEverything() {
3104 android_atomic_or(1, &mRepaintEverything);
3105 signalTransaction();
3106}
3107
3108// ---------------------------------------------------------------------------
3109// Capture screen into an IGraphiBufferProducer
3110// ---------------------------------------------------------------------------
3111
3112/* The code below is here to handle b/8734824
3113 *
3114 * We create a IGraphicBufferProducer wrapper that forwards all calls
3115 * from the surfaceflinger thread to the calling binder thread, where they
3116 * are executed. This allows the calling thread in the calling process to be
3117 * reused and not depend on having "enough" binder threads to handle the
3118 * requests.
3119 */
3120class GraphicProducerWrapper : public BBinder, public MessageHandler {
3121 /* Parts of GraphicProducerWrapper are run on two different threads,
3122 * communicating by sending messages via Looper but also by shared member
3123 * data. Coherence maintenance is subtle and in places implicit (ugh).
3124 *
3125 * Don't rely on Looper's sendMessage/handleMessage providing
3126 * release/acquire semantics for any data not actually in the Message.
3127 * Data going from surfaceflinger to binder threads needs to be
3128 * synchronized explicitly.
3129 *
3130 * Barrier open/wait do provide release/acquire semantics. This provides
3131 * implicit synchronization for data coming back from binder to
3132 * surfaceflinger threads.
3133 */
3134
3135 sp<IGraphicBufferProducer> impl;
3136 sp<Looper> looper;
3137 status_t result;
3138 bool exitPending;
3139 bool exitRequested;
3140 Barrier barrier;
3141 uint32_t code;
3142 Parcel const* data;
3143 Parcel* reply;
3144
3145 enum {
3146 MSG_API_CALL,
3147 MSG_EXIT
3148 };
3149
3150 /*
3151 * Called on surfaceflinger thread. This is called by our "fake"
3152 * BpGraphicBufferProducer. We package the data and reply Parcel and
3153 * forward them to the binder thread.
3154 */
3155 virtual status_t transact(uint32_t code,
3156 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3157 this->code = code;
3158 this->data = &data;
3159 this->reply = reply;
3160 if (exitPending) {
3161 // if we've exited, we run the message synchronously right here.
3162 // note (JH): as far as I can tell from looking at the code, this
3163 // never actually happens. if it does, i'm not sure if it happens
3164 // on the surfaceflinger or binder thread.
3165 handleMessage(Message(MSG_API_CALL));
3166 } else {
3167 barrier.close();
3168 // Prevent stores to this->{code, data, reply} from being
3169 // reordered later than the construction of Message.
3170 atomic_thread_fence(memory_order_release);
3171 looper->sendMessage(this, Message(MSG_API_CALL));
3172 barrier.wait();
3173 }
3174 return result;
3175 }
3176
3177 /*
3178 * here we run on the binder thread. All we've got to do is
3179 * call the real BpGraphicBufferProducer.
3180 */
3181 virtual void handleMessage(const Message& message) {
3182 int what = message.what;
3183 // Prevent reads below from happening before the read from Message
3184 atomic_thread_fence(memory_order_acquire);
3185 if (what == MSG_API_CALL) {
3186 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3187 barrier.open();
3188 } else if (what == MSG_EXIT) {
3189 exitRequested = true;
3190 }
3191 }
3192
3193public:
3194 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3195 : impl(impl),
3196 looper(new Looper(true)),
3197 result(NO_ERROR),
3198 exitPending(false),
3199 exitRequested(false),
3200 code(0),
3201 data(NULL),
3202 reply(NULL)
3203 {}
3204
3205 // Binder thread
3206 status_t waitForResponse() {
3207 do {
3208 looper->pollOnce(-1);
3209 } while (!exitRequested);
3210 return result;
3211 }
3212
3213 // Client thread
3214 void exit(status_t result) {
3215 this->result = result;
3216 exitPending = true;
3217 // Ensure this->result is visible to the binder thread before it
3218 // handles the message.
3219 atomic_thread_fence(memory_order_release);
3220 looper->sendMessage(this, Message(MSG_EXIT));
3221 }
3222};
3223
3224
3225status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3226 const sp<IGraphicBufferProducer>& producer,
3227 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3228 uint32_t minLayerZ, uint32_t maxLayerZ,
3229 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3230
3231 if (CC_UNLIKELY(display == 0))
3232 return BAD_VALUE;
3233
3234 if (CC_UNLIKELY(producer == 0))
3235 return BAD_VALUE;
3236
3237 // if we have secure windows on this display, never allow the screen capture
3238 // unless the producer interface is local (i.e.: we can take a screenshot for
3239 // ourselves).
3240 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3241
3242 // Convert to surfaceflinger's internal rotation type.
3243 Transform::orientation_flags rotationFlags;
3244 switch (rotation) {
3245 case ISurfaceComposer::eRotateNone:
3246 rotationFlags = Transform::ROT_0;
3247 break;
3248 case ISurfaceComposer::eRotate90:
3249 rotationFlags = Transform::ROT_90;
3250 break;
3251 case ISurfaceComposer::eRotate180:
3252 rotationFlags = Transform::ROT_180;
3253 break;
3254 case ISurfaceComposer::eRotate270:
3255 rotationFlags = Transform::ROT_270;
3256 break;
3257 default:
3258 rotationFlags = Transform::ROT_0;
3259 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3260 break;
3261 }
3262
3263 class MessageCaptureScreen : public MessageBase {
3264 SurfaceFlinger* flinger;
3265 sp<IBinder> display;
3266 sp<IGraphicBufferProducer> producer;
3267 Rect sourceCrop;
3268 uint32_t reqWidth, reqHeight;
3269 uint32_t minLayerZ,maxLayerZ;
3270 bool useIdentityTransform;
3271 Transform::orientation_flags rotation;
3272 status_t result;
3273 bool isLocalScreenshot;
3274 public:
3275 MessageCaptureScreen(SurfaceFlinger* flinger,
3276 const sp<IBinder>& display,
3277 const sp<IGraphicBufferProducer>& producer,
3278 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3279 uint32_t minLayerZ, uint32_t maxLayerZ,
3280 bool useIdentityTransform,
3281 Transform::orientation_flags rotation,
3282 bool isLocalScreenshot)
3283 : flinger(flinger), display(display), producer(producer),
3284 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3285 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3286 useIdentityTransform(useIdentityTransform),
3287 rotation(rotation), result(PERMISSION_DENIED),
3288 isLocalScreenshot(isLocalScreenshot)
3289 {
3290 }
3291 status_t getResult() const {
3292 return result;
3293 }
3294 virtual bool handler() {
3295 Mutex::Autolock _l(flinger->mStateLock);
3296 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3297 result = flinger->captureScreenImplLocked(hw, producer,
3298 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3299 useIdentityTransform, rotation, isLocalScreenshot);
3300 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3301 return true;
3302 }
3303 };
3304
Dan Stoza9e56aa02015-11-02 13:00:03 -08003305 // this creates a "fake" BBinder which will serve as a "fake" remote
3306 // binder to receive the marshaled calls and forward them to the
3307 // real remote (a BpGraphicBufferProducer)
3308 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3309
3310 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3311 // which does the marshaling work forwards to our "fake remote" above.
3312 sp<MessageBase> msg = new MessageCaptureScreen(this,
3313 display, IGraphicBufferProducer::asInterface( wrapper ),
3314 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3315 useIdentityTransform, rotationFlags, isLocalScreenshot);
3316
3317 status_t res = postMessageAsync(msg);
3318 if (res == NO_ERROR) {
3319 res = wrapper->waitForResponse();
3320 }
3321 return res;
3322}
3323
3324
3325void SurfaceFlinger::renderScreenImplLocked(
3326 const sp<const DisplayDevice>& hw,
3327 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3328 uint32_t minLayerZ, uint32_t maxLayerZ,
3329 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3330{
3331 ATRACE_CALL();
3332 RenderEngine& engine(getRenderEngine());
3333
3334 // get screen geometry
3335 const int32_t hw_w = hw->getWidth();
3336 const int32_t hw_h = hw->getHeight();
3337 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3338 static_cast<int32_t>(reqHeight) != hw_h;
3339
3340 // if a default or invalid sourceCrop is passed in, set reasonable values
3341 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3342 !sourceCrop.isValid()) {
3343 sourceCrop.setLeftTop(Point(0, 0));
3344 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3345 }
3346
3347 // ensure that sourceCrop is inside screen
3348 if (sourceCrop.left < 0) {
3349 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3350 }
3351 if (sourceCrop.right > hw_w) {
3352 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3353 }
3354 if (sourceCrop.top < 0) {
3355 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3356 }
3357 if (sourceCrop.bottom > hw_h) {
3358 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3359 }
3360
3361 // make sure to clear all GL error flags
3362 engine.checkErrors();
3363
3364 // set-up our viewport
3365 engine.setViewportAndProjection(
3366 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3367 engine.disableTexturing();
3368
3369 // redraw the screen entirely...
3370 engine.clearWithColor(0, 0, 0, 1);
3371
3372 const LayerVector& layers( mDrawingState.layersSortedByZ );
3373 const size_t count = layers.size();
3374 for (size_t i=0 ; i<count ; ++i) {
3375 const sp<Layer>& layer(layers[i]);
3376 const Layer::State& state(layer->getDrawingState());
3377 if (state.layerStack == hw->getLayerStack()) {
3378 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3379 if (layer->isVisible()) {
3380 if (filtering) layer->setFiltering(true);
3381 layer->draw(hw, useIdentityTransform);
3382 if (filtering) layer->setFiltering(false);
3383 }
3384 }
3385 }
3386 }
3387
3388 // compositionComplete is needed for older driver
3389 hw->compositionComplete();
3390 hw->setViewportAndProjection();
3391}
3392
3393
3394status_t SurfaceFlinger::captureScreenImplLocked(
3395 const sp<const DisplayDevice>& hw,
3396 const sp<IGraphicBufferProducer>& producer,
3397 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3398 uint32_t minLayerZ, uint32_t maxLayerZ,
3399 bool useIdentityTransform, Transform::orientation_flags rotation,
3400 bool isLocalScreenshot)
3401{
3402 ATRACE_CALL();
3403
3404 // get screen geometry
3405 uint32_t hw_w = hw->getWidth();
3406 uint32_t hw_h = hw->getHeight();
3407
3408 if (rotation & Transform::ROT_90) {
3409 std::swap(hw_w, hw_h);
3410 }
3411
3412 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3413 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3414 reqWidth, reqHeight, hw_w, hw_h);
3415 return BAD_VALUE;
3416 }
3417
3418 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3419 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3420
3421 bool secureLayerIsVisible = false;
3422 const LayerVector& layers(mDrawingState.layersSortedByZ);
3423 const size_t count = layers.size();
3424 for (size_t i = 0 ; i < count ; ++i) {
3425 const sp<Layer>& layer(layers[i]);
3426 const Layer::State& state(layer->getDrawingState());
3427 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3428 state.z <= maxLayerZ && layer->isVisible() &&
3429 layer->isSecure()) {
3430 secureLayerIsVisible = true;
3431 }
3432 }
3433
3434 if (!isLocalScreenshot && secureLayerIsVisible) {
3435 ALOGW("FB is protected: PERMISSION_DENIED");
3436 return PERMISSION_DENIED;
3437 }
3438
3439 // create a surface (because we're a producer, and we need to
3440 // dequeue/queue a buffer)
3441 sp<Surface> sur = new Surface(producer, false);
3442 ANativeWindow* window = sur.get();
3443
3444 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3445 if (result == NO_ERROR) {
3446 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3447 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3448
3449 int err = 0;
3450 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3451 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3452 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3453 err |= native_window_set_usage(window, usage);
3454
3455 if (err == NO_ERROR) {
3456 ANativeWindowBuffer* buffer;
3457 /* TODO: Once we have the sync framework everywhere this can use
3458 * server-side waits on the fence that dequeueBuffer returns.
3459 */
3460 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3461 if (result == NO_ERROR) {
3462 int syncFd = -1;
3463 // create an EGLImage from the buffer so we can later
3464 // turn it into a texture
3465 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3466 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3467 if (image != EGL_NO_IMAGE_KHR) {
3468 // this binds the given EGLImage as a framebuffer for the
3469 // duration of this scope.
3470 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3471 if (imageBond.getStatus() == NO_ERROR) {
3472 // this will in fact render into our dequeued buffer
3473 // via an FBO, which means we didn't have to create
3474 // an EGLSurface and therefore we're not
3475 // dependent on the context's EGLConfig.
3476 renderScreenImplLocked(
3477 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3478 useIdentityTransform, rotation);
3479
3480 // Attempt to create a sync khr object that can produce a sync point. If that
3481 // isn't available, create a non-dupable sync object in the fallback path and
3482 // wait on it directly.
3483 EGLSyncKHR sync;
3484 if (!DEBUG_SCREENSHOTS) {
3485 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3486 // native fence fd will not be populated until flush() is done.
3487 getRenderEngine().flush();
3488 } else {
3489 sync = EGL_NO_SYNC_KHR;
3490 }
3491 if (sync != EGL_NO_SYNC_KHR) {
3492 // get the sync fd
3493 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3494 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3495 ALOGW("captureScreen: failed to dup sync khr object");
3496 syncFd = -1;
3497 }
3498 eglDestroySyncKHR(mEGLDisplay, sync);
3499 } else {
3500 // fallback path
3501 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3502 if (sync != EGL_NO_SYNC_KHR) {
3503 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3504 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3505 EGLint eglErr = eglGetError();
3506 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3507 ALOGW("captureScreen: fence wait timed out");
3508 } else {
3509 ALOGW_IF(eglErr != EGL_SUCCESS,
3510 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3511 }
3512 eglDestroySyncKHR(mEGLDisplay, sync);
3513 } else {
3514 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3515 }
3516 }
3517 if (DEBUG_SCREENSHOTS) {
3518 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3519 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3520 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3521 hw, minLayerZ, maxLayerZ);
3522 delete [] pixels;
3523 }
3524
3525 } else {
3526 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3527 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003528 window->cancelBuffer(window, buffer, syncFd);
3529 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003530 }
3531 // destroy our image
3532 eglDestroyImageKHR(mEGLDisplay, image);
3533 } else {
3534 result = BAD_VALUE;
3535 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003536 if (buffer) {
3537 // queueBuffer takes ownership of syncFd
3538 result = window->queueBuffer(window, buffer, syncFd);
3539 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003540 }
3541 } else {
3542 result = BAD_VALUE;
3543 }
3544 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3545 }
3546
3547 return result;
3548}
3549
3550void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3551 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3552 if (DEBUG_SCREENSHOTS) {
3553 for (size_t y=0 ; y<h ; y++) {
3554 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3555 for (size_t x=0 ; x<w ; x++) {
3556 if (p[x] != 0xFF000000) return;
3557 }
3558 }
3559 ALOGE("*** we just took a black screenshot ***\n"
3560 "requested minz=%d, maxz=%d, layerStack=%d",
3561 minLayerZ, maxLayerZ, hw->getLayerStack());
3562 const LayerVector& layers( mDrawingState.layersSortedByZ );
3563 const size_t count = layers.size();
3564 for (size_t i=0 ; i<count ; ++i) {
3565 const sp<Layer>& layer(layers[i]);
3566 const Layer::State& state(layer->getDrawingState());
3567 const bool visible = (state.layerStack == hw->getLayerStack())
3568 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3569 && (layer->isVisible());
3570 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3571 visible ? '+' : '-',
3572 i, layer->getName().string(), state.layerStack, state.z,
3573 layer->isVisible(), state.flags, state.alpha);
3574 }
3575 }
3576}
3577
3578// ---------------------------------------------------------------------------
3579
3580SurfaceFlinger::LayerVector::LayerVector() {
3581}
3582
3583SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3584 : SortedVector<sp<Layer> >(rhs) {
3585}
3586
3587int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3588 const void* rhs) const
3589{
3590 // sort layers per layer-stack, then by z-order and finally by sequence
3591 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3592 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3593
3594 uint32_t ls = l->getCurrentState().layerStack;
3595 uint32_t rs = r->getCurrentState().layerStack;
3596 if (ls != rs)
3597 return ls - rs;
3598
3599 uint32_t lz = l->getCurrentState().z;
3600 uint32_t rz = r->getCurrentState().z;
3601 if (lz != rz)
3602 return lz - rz;
3603
3604 return l->sequence - r->sequence;
3605}
3606
3607// ---------------------------------------------------------------------------
3608
3609SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3610 : type(DisplayDevice::DISPLAY_ID_INVALID),
3611 layerStack(DisplayDevice::NO_LAYER_STACK),
3612 orientation(0),
3613 width(0),
3614 height(0),
3615 isSecure(false) {
3616}
3617
3618SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3619 DisplayDevice::DisplayType type, bool isSecure)
3620 : type(type),
3621 layerStack(DisplayDevice::NO_LAYER_STACK),
3622 orientation(0),
3623 width(0),
3624 height(0),
3625 isSecure(isSecure) {
3626 viewport.makeInvalid();
3627 frame.makeInvalid();
3628}
3629
3630// ---------------------------------------------------------------------------
3631
3632}; // namespace android
3633
3634
3635#if defined(__gl_h_)
3636#error "don't include gl/gl.h in this file"
3637#endif
3638
3639#if defined(__gl2_h_)
3640#error "don't include gl2/gl2.h in this file"
3641#endif