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