1 /*
2  * Copyright 2015 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 #ifndef ANDROID_SF_HWC2_ON_1_ADAPTER_H
18 #define ANDROID_SF_HWC2_ON_1_ADAPTER_H
19 
20 #define HWC2_INCLUDE_STRINGIFICATION
21 #define HWC2_USE_CPP11
22 #include <hardware/hwcomposer2.h>
23 #undef HWC2_INCLUDE_STRINGIFICATION
24 #undef HWC2_USE_CPP11
25 
26 #include "MiniFence.h"
27 
28 #include <atomic>
29 #include <map>
30 #include <mutex>
31 #include <queue>
32 #include <set>
33 #include <unordered_map>
34 #include <unordered_set>
35 #include <vector>
36 
37 struct hwc_composer_device_1;
38 struct hwc_display_contents_1;
39 struct hwc_layer_1;
40 
41 namespace android {
42 
43 // For devices unable to provide an implementation of HWC2 (see hwcomposer2.h),
44 // we provide an adapter able to talk to HWC1 (see hwcomposer.h). It translates
45 // streamed function calls ala HWC2 model to batched array of structs calls ala
46 // HWC1 model.
47 class HWC2On1Adapter : public hwc2_device_t
48 {
49 public:
50     explicit HWC2On1Adapter(struct hwc_composer_device_1* hwc1Device);
51     ~HWC2On1Adapter();
52 
getHwc1Device()53     struct hwc_composer_device_1* getHwc1Device() const { return mHwc1Device; }
getHwc1MinorVersion()54     uint8_t getHwc1MinorVersion() const { return mHwc1MinorVersion; }
55 
56 private:
getAdapter(hwc2_device_t * device)57     static inline HWC2On1Adapter* getAdapter(hwc2_device_t* device) {
58         return static_cast<HWC2On1Adapter*>(device);
59     }
60 
61     // getCapabilities
62 
63     void doGetCapabilities(uint32_t* outCount,
64             int32_t* /*hwc2_capability_t*/ outCapabilities);
getCapabilitiesHook(hwc2_device_t * device,uint32_t * outCount,int32_t * outCapabilities)65     static void getCapabilitiesHook(hwc2_device_t* device, uint32_t* outCount,
66             int32_t* /*hwc2_capability_t*/ outCapabilities) {
67         getAdapter(device)->doGetCapabilities(outCount, outCapabilities);
68     }
69 
supportsBackgroundColor()70     bool supportsBackgroundColor() {
71         return mHwc1SupportsBackgroundColor;
72     }
73 
74     // getFunction
75 
76     hwc2_function_pointer_t doGetFunction(HWC2::FunctionDescriptor descriptor);
getFunctionHook(hwc2_device_t * device,int32_t intDesc)77     static hwc2_function_pointer_t getFunctionHook(hwc2_device_t* device,
78             int32_t intDesc) {
79         auto descriptor = static_cast<HWC2::FunctionDescriptor>(intDesc);
80         return getAdapter(device)->doGetFunction(descriptor);
81     }
82 
83     // Device functions
84 
85     HWC2::Error createVirtualDisplay(uint32_t width, uint32_t height,
86             hwc2_display_t* outDisplay);
createVirtualDisplayHook(hwc2_device_t * device,uint32_t width,uint32_t height,int32_t *,hwc2_display_t * outDisplay)87     static int32_t createVirtualDisplayHook(hwc2_device_t* device,
88             uint32_t width, uint32_t height, int32_t* /*format*/,
89             hwc2_display_t* outDisplay) {
90         // HWC1 implementations cannot override the buffer format requested by
91         // the consumer
92         auto error = getAdapter(device)->createVirtualDisplay(width, height,
93                 outDisplay);
94         return static_cast<int32_t>(error);
95     }
96 
97     HWC2::Error destroyVirtualDisplay(hwc2_display_t display);
destroyVirtualDisplayHook(hwc2_device_t * device,hwc2_display_t display)98     static int32_t destroyVirtualDisplayHook(hwc2_device_t* device,
99             hwc2_display_t display) {
100         auto error = getAdapter(device)->destroyVirtualDisplay(display);
101         return static_cast<int32_t>(error);
102     }
103 
104     std::string mDumpString;
105     void dump(uint32_t* outSize, char* outBuffer);
dumpHook(hwc2_device_t * device,uint32_t * outSize,char * outBuffer)106     static void dumpHook(hwc2_device_t* device, uint32_t* outSize,
107             char* outBuffer) {
108         getAdapter(device)->dump(outSize, outBuffer);
109     }
110 
111     uint32_t getMaxVirtualDisplayCount();
getMaxVirtualDisplayCountHook(hwc2_device_t * device)112     static uint32_t getMaxVirtualDisplayCountHook(hwc2_device_t* device) {
113         return getAdapter(device)->getMaxVirtualDisplayCount();
114     }
115 
116     HWC2::Error registerCallback(HWC2::Callback descriptor,
117             hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer);
registerCallbackHook(hwc2_device_t * device,int32_t intDesc,hwc2_callback_data_t callbackData,hwc2_function_pointer_t pointer)118     static int32_t registerCallbackHook(hwc2_device_t* device,
119             int32_t intDesc, hwc2_callback_data_t callbackData,
120             hwc2_function_pointer_t pointer) {
121         auto descriptor = static_cast<HWC2::Callback>(intDesc);
122         auto error = getAdapter(device)->registerCallback(descriptor,
123                 callbackData, pointer);
124         return static_cast<int32_t>(error);
125     }
126 
127     // Display functions
128 
129     class Layer;
130 
131     class SortLayersByZ {
132         public:
133          bool operator()(const std::shared_ptr<Layer>& lhs,
134                          const std::shared_ptr<Layer>& rhs) const;
135     };
136 
137     // The semantics of the fences returned by the device differ between
138     // hwc1.set() and hwc2.present(). Read hwcomposer.h and hwcomposer2.h
139     // for more information.
140     //
141     // Release fences in hwc1 are obtained on set() for a frame n and signaled
142     // when the layer buffer is not needed for read operations anymore
143     // (typically on frame n+1). In HWC2, release fences are obtained with a
144     // special call after present() for frame n. These fences signal
145     // on frame n: More specifically, the fence for a given buffer provided in
146     // frame n will signal when the prior buffer is no longer required.
147     //
148     // A retire fence (HWC1) is signaled when a composition is replaced
149     // on the panel whereas a present fence (HWC2) is signaled when a
150     // composition starts to be displayed on a panel.
151     //
152     // The HWC2to1Adapter emulates the new fence semantics for a frame
153     // n by returning the fence from frame n-1. For frame 0, the adapter
154     // returns NO_FENCE.
155     class DeferredFence {
156         public:
DeferredFence()157             DeferredFence()
158               : mFences({MiniFence::NO_FENCE, MiniFence::NO_FENCE}) {}
159 
add(int32_t fenceFd)160             void add(int32_t fenceFd) {
161                 mFences.emplace(new MiniFence(fenceFd));
162                 mFences.pop();
163             }
164 
get()165             const sp<MiniFence>& get() const {
166                 return mFences.front();
167             }
168 
169         private:
170             // There are always two fences in this queue.
171             std::queue<sp<MiniFence>> mFences;
172     };
173 
174     class FencedBuffer {
175         public:
FencedBuffer()176             FencedBuffer() : mBuffer(nullptr), mFence(MiniFence::NO_FENCE) {}
177 
setBuffer(buffer_handle_t buffer)178             void setBuffer(buffer_handle_t buffer) { mBuffer = buffer; }
setFence(int fenceFd)179             void setFence(int fenceFd) { mFence = new MiniFence(fenceFd); }
180 
getBuffer()181             buffer_handle_t getBuffer() const { return mBuffer; }
getFence()182             int getFence() const { return mFence->dup(); }
183 
184         private:
185             buffer_handle_t mBuffer;
186             sp<MiniFence> mFence;
187     };
188 
189     class Display {
190         public:
191             Display(HWC2On1Adapter& device, HWC2::DisplayType type);
192 
getId()193             hwc2_display_t getId() const { return mId; }
getDevice()194             HWC2On1Adapter& getDevice() const { return mDevice; }
195 
196             // Does not require locking because it is set before adding the
197             // Displays to the Adapter's list of displays
setHwc1Id(int32_t id)198             void setHwc1Id(int32_t id) { mHwc1Id = id; }
getHwc1Id()199             int32_t getHwc1Id() const { return mHwc1Id; }
200 
201             // HWC2 Display functions
202             HWC2::Error acceptChanges();
203             HWC2::Error createLayer(hwc2_layer_t* outLayerId);
204             HWC2::Error destroyLayer(hwc2_layer_t layerId);
205             HWC2::Error getActiveConfig(hwc2_config_t* outConfigId);
206             HWC2::Error getAttribute(hwc2_config_t configId,
207                     HWC2::Attribute attribute, int32_t* outValue);
208             HWC2::Error getChangedCompositionTypes(uint32_t* outNumElements,
209                     hwc2_layer_t* outLayers, int32_t* outTypes);
210             HWC2::Error getColorModes(uint32_t* outNumModes, int32_t* outModes);
211             HWC2::Error getConfigs(uint32_t* outNumConfigs,
212                     hwc2_config_t* outConfigIds);
213             HWC2::Error getDozeSupport(int32_t* outSupport);
214             HWC2::Error getHdrCapabilities(uint32_t* outNumTypes,
215                     int32_t* outTypes, float* outMaxLuminance,
216                     float* outMaxAverageLuminance, float* outMinLuminance);
217             HWC2::Error getName(uint32_t* outSize, char* outName);
218             HWC2::Error getReleaseFences(uint32_t* outNumElements,
219                     hwc2_layer_t* outLayers, int32_t* outFences);
220             HWC2::Error getRequests(int32_t* outDisplayRequests,
221                     uint32_t* outNumElements, hwc2_layer_t* outLayers,
222                     int32_t* outLayerRequests);
223             HWC2::Error getType(int32_t* outType);
224 
225             // Since HWC1 "presents" (called "set" in HWC1) all Displays
226             // at once, the first call to any Display::present will trigger
227             // present() on all Displays in the Device. Subsequent calls without
228             // first calling validate() are noop (except for duping/returning
229             // the retire fence).
230             HWC2::Error present(int32_t* outRetireFence);
231 
232             HWC2::Error setActiveConfig(hwc2_config_t configId);
233             HWC2::Error setClientTarget(buffer_handle_t target,
234                     int32_t acquireFence, int32_t dataspace,
235                     hwc_region_t damage);
236             HWC2::Error setColorMode(android_color_mode_t mode);
237             HWC2::Error setColorTransform(android_color_transform_t hint);
238             HWC2::Error setOutputBuffer(buffer_handle_t buffer,
239                     int32_t releaseFence);
240             HWC2::Error setPowerMode(HWC2::PowerMode mode);
241             HWC2::Error setVsyncEnabled(HWC2::Vsync enabled);
242 
243             // Since HWC1 "validates" (called "prepare" in HWC1) all Displays
244             // at once, the first call to any Display::validate() will trigger
245             // validate() on all other Displays in the Device.
246             HWC2::Error validate(uint32_t* outNumTypes,
247                     uint32_t* outNumRequests);
248 
249             HWC2::Error updateLayerZ(hwc2_layer_t layerId, uint32_t z);
250 
251             HWC2::Error getClientTargetSupport(uint32_t width, uint32_t height,
252                      int32_t format, int32_t dataspace);
253 
254             // Read configs from HWC1 device
255             void populateConfigs();
256 
257             // Set configs for a virtual display
258             void populateConfigs(uint32_t width, uint32_t height);
259 
260             bool prepare();
261 
262             // Called after hwc.prepare() with responses from the device.
263             void generateChanges();
264 
265             bool hasChanges() const;
266             HWC2::Error set(hwc_display_contents_1& hwcContents);
267             void addRetireFence(int fenceFd);
268             void addReleaseFences(const hwc_display_contents_1& hwcContents);
269 
270             bool hasColorTransform() const;
271 
272             std::string dump() const;
273 
274             // Return a rect from the pool allocated during validate()
275             hwc_rect_t* GetRects(size_t numRects);
276 
277             hwc_display_contents_1* getDisplayContents();
278 
markGeometryChanged()279             void markGeometryChanged() { mGeometryChanged = true; }
resetGeometryMarker()280             void resetGeometryMarker() { mGeometryChanged = false;}
281         private:
282             class Config {
283                 public:
Config(Display & display)284                     Config(Display& display)
285                       : mDisplay(display),
286                         mId(0),
287                         mAttributes() {}
288 
isOnDisplay(const Display & display)289                     bool isOnDisplay(const Display& display) const {
290                         return display.getId() == mDisplay.getId();
291                     }
292 
293                     void setAttribute(HWC2::Attribute attribute, int32_t value);
294                     int32_t getAttribute(HWC2::Attribute attribute) const;
295 
296                     void setHwc1Id(uint32_t id);
297                     bool hasHwc1Id(uint32_t id) const;
298                     HWC2::Error getColorModeForHwc1Id(uint32_t id,
299                             android_color_mode_t *outMode) const;
300                     HWC2::Error getHwc1IdForColorMode(android_color_mode_t mode,
301                             uint32_t* outId) const;
302 
setId(hwc2_config_t id)303                     void setId(hwc2_config_t id) { mId = id; }
getId()304                     hwc2_config_t getId() const { return mId; }
305 
306                     // Attempts to merge two configs that differ only in color
307                     // mode. Returns whether the merge was successful
308                     bool merge(const Config& other);
309 
310                     std::set<android_color_mode_t> getColorModes() const;
311 
312                     // splitLine divides the output into two lines suitable for
313                     // dumpsys SurfaceFlinger
314                     std::string toString(bool splitLine = false) const;
315 
316                 private:
317                     Display& mDisplay;
318                     hwc2_config_t mId;
319                     std::unordered_map<HWC2::Attribute, int32_t> mAttributes;
320 
321                     // Maps from color transform to HWC1 config ID
322                     std::unordered_map<android_color_mode_t, uint32_t> mHwc1Ids;
323             };
324 
325             // Stores changes requested from the device upon calling prepare().
326             // Handles change request to:
327             //   - Layer composition type.
328             //   - Layer hints.
329             class Changes {
330                 public:
getNumTypes()331                     uint32_t getNumTypes() const {
332                         return static_cast<uint32_t>(mTypeChanges.size());
333                     }
334 
getNumLayerRequests()335                     uint32_t getNumLayerRequests() const {
336                         return static_cast<uint32_t>(mLayerRequests.size());
337                     }
338 
339                     const std::unordered_map<hwc2_layer_t, HWC2::Composition>&
getTypeChanges()340                             getTypeChanges() const {
341                         return mTypeChanges;
342                     }
343 
344                     const std::unordered_map<hwc2_layer_t, HWC2::LayerRequest>&
getLayerRequests()345                             getLayerRequests() const {
346                         return mLayerRequests;
347                     }
348 
addTypeChange(hwc2_layer_t layerId,HWC2::Composition type)349                     void addTypeChange(hwc2_layer_t layerId,
350                             HWC2::Composition type) {
351                         mTypeChanges.insert({layerId, type});
352                     }
353 
clearTypeChanges()354                     void clearTypeChanges() { mTypeChanges.clear(); }
355 
addLayerRequest(hwc2_layer_t layerId,HWC2::LayerRequest request)356                     void addLayerRequest(hwc2_layer_t layerId,
357                             HWC2::LayerRequest request) {
358                         mLayerRequests.insert({layerId, request});
359                     }
360 
361                 private:
362                     std::unordered_map<hwc2_layer_t, HWC2::Composition>
363                             mTypeChanges;
364                     std::unordered_map<hwc2_layer_t, HWC2::LayerRequest>
365                             mLayerRequests;
366             };
367 
368             std::shared_ptr<const Config>
369                     getConfig(hwc2_config_t configId) const;
370 
371             void populateColorModes();
372             void initializeActiveConfig();
373 
374             // Creates a bi-directional mapping between index in HWC1
375             // prepare/set array and Layer object. Stores mapping in
376             // mHwc1LayerMap and also updates Layer's attribute mHwc1Id.
377             void assignHwc1LayerIds();
378 
379             // Called after a response to prepare() has been received:
380             // Ingest composition type changes requested by the device.
381             void updateTypeChanges(const struct hwc_layer_1& hwc1Layer,
382                     const Layer& layer);
383 
384             // Called after a response to prepare() has been received:
385             // Ingest layer hint changes requested by the device.
386             void updateLayerRequests(const struct hwc_layer_1& hwc1Layer,
387                     const Layer& layer);
388 
389             // Set all fields in HWC1 comm array for layer containing the
390             // HWC_FRAMEBUFFER_TARGET (always the last layer).
391             void prepareFramebufferTarget();
392 
393             // Display ID generator.
394             static std::atomic<hwc2_display_t> sNextId;
395             const hwc2_display_t mId;
396 
397 
398             HWC2On1Adapter& mDevice;
399 
400             // The state of this display should only be modified from
401             // SurfaceFlinger's main loop, with the exception of when dump is
402             // called. To prevent a bad state from crashing us during a dump
403             // call, all public calls into Display must acquire this mutex.
404             //
405             // It is recursive because we don't want to deadlock in validate
406             // (or present) when we call HWC2On1Adapter::prepareAllDisplays
407             // (or setAllDisplays), which calls back into Display functions
408             // which require locking.
409             mutable std::recursive_mutex mStateMutex;
410 
411             // Allocate RAM able to store all layers and rects used for
412             // communication with HWC1. Place allocated RAM in variable
413             // mHwc1RequestedContents.
414             void allocateRequestedContents();
415 
416             // Array of structs exchanged between client and hwc1 device.
417             // Sent to device upon calling prepare().
418             std::unique_ptr<hwc_display_contents_1> mHwc1RequestedContents;
419     private:
420             DeferredFence mRetireFence;
421 
422             // Will only be non-null after the Display has been validated and
423             // before it has been presented
424             std::unique_ptr<Changes> mChanges;
425 
426             int32_t mHwc1Id;
427 
428             std::vector<std::shared_ptr<Config>> mConfigs;
429             std::shared_ptr<const Config> mActiveConfig;
430             std::set<android_color_mode_t> mColorModes;
431             android_color_mode_t mActiveColorMode;
432             std::string mName;
433             HWC2::DisplayType mType;
434             HWC2::PowerMode mPowerMode;
435             HWC2::Vsync mVsyncEnabled;
436 
437             // Used to populate HWC1 HWC_FRAMEBUFFER_TARGET layer
438             FencedBuffer mClientTarget;
439 
440 
441             FencedBuffer mOutputBuffer;
442 
443             bool mHasColorTransform;
444 
445             // All layers this Display is aware of.
446             std::multiset<std::shared_ptr<Layer>, SortLayersByZ> mLayers;
447 
448             // Mapping between layer index in array of hwc_display_contents_1*
449             // passed to HWC1 during validate/set and Layer object.
450             std::unordered_map<size_t, std::shared_ptr<Layer>> mHwc1LayerMap;
451 
452             // All communication with HWC1 via prepare/set is done with one
453             // alloc. This pointer is pointing to a pool of hwc_rect_t.
454             size_t mNumAvailableRects;
455             hwc_rect_t* mNextAvailableRect;
456 
457             // True if any of the Layers contained in this Display have been
458             // updated with anything other than a buffer since last call to
459             // Display::set()
460             bool mGeometryChanged;
461     };
462 
463     // Utility template calling a Display object method directly based on the
464     // hwc2_display_t displayId parameter.
465     template <typename ...Args>
callDisplayFunction(hwc2_device_t * device,hwc2_display_t displayId,HWC2::Error (Display::* member)(Args...),Args...args)466     static int32_t callDisplayFunction(hwc2_device_t* device,
467             hwc2_display_t displayId, HWC2::Error (Display::*member)(Args...),
468             Args... args) {
469         auto display = getAdapter(device)->getDisplay(displayId);
470         if (!display) {
471             return static_cast<int32_t>(HWC2::Error::BadDisplay);
472         }
473         auto error = ((*display).*member)(std::forward<Args>(args)...);
474         return static_cast<int32_t>(error);
475     }
476 
477     template <typename MF, MF memFunc, typename ...Args>
displayHook(hwc2_device_t * device,hwc2_display_t displayId,Args...args)478     static int32_t displayHook(hwc2_device_t* device, hwc2_display_t displayId,
479             Args... args) {
480         return HWC2On1Adapter::callDisplayFunction(device, displayId, memFunc,
481                 std::forward<Args>(args)...);
482     }
483 
getDisplayAttributeHook(hwc2_device_t * device,hwc2_display_t display,hwc2_config_t config,int32_t intAttribute,int32_t * outValue)484     static int32_t getDisplayAttributeHook(hwc2_device_t* device,
485             hwc2_display_t display, hwc2_config_t config,
486             int32_t intAttribute, int32_t* outValue) {
487         auto attribute = static_cast<HWC2::Attribute>(intAttribute);
488         return callDisplayFunction(device, display, &Display::getAttribute,
489                 config, attribute, outValue);
490     }
491 
setColorTransformHook(hwc2_device_t * device,hwc2_display_t display,const float *,int32_t intHint)492     static int32_t setColorTransformHook(hwc2_device_t* device,
493             hwc2_display_t display, const float* /*matrix*/,
494             int32_t /*android_color_transform_t*/ intHint) {
495         // We intentionally throw away the matrix, because if the hint is
496         // anything other than IDENTITY, we have to fall back to client
497         // composition anyway
498         auto hint = static_cast<android_color_transform_t>(intHint);
499         return callDisplayFunction(device, display, &Display::setColorTransform,
500                 hint);
501     }
502 
setColorModeHook(hwc2_device_t * device,hwc2_display_t display,int32_t intMode)503     static int32_t setColorModeHook(hwc2_device_t* device,
504             hwc2_display_t display, int32_t /*android_color_mode_t*/ intMode) {
505         auto mode = static_cast<android_color_mode_t>(intMode);
506         return callDisplayFunction(device, display, &Display::setColorMode,
507                 mode);
508     }
509 
setPowerModeHook(hwc2_device_t * device,hwc2_display_t display,int32_t intMode)510     static int32_t setPowerModeHook(hwc2_device_t* device,
511             hwc2_display_t display, int32_t intMode) {
512         auto mode = static_cast<HWC2::PowerMode>(intMode);
513         return callDisplayFunction(device, display, &Display::setPowerMode,
514                 mode);
515     }
516 
setVsyncEnabledHook(hwc2_device_t * device,hwc2_display_t display,int32_t intEnabled)517     static int32_t setVsyncEnabledHook(hwc2_device_t* device,
518             hwc2_display_t display, int32_t intEnabled) {
519         auto enabled = static_cast<HWC2::Vsync>(intEnabled);
520         return callDisplayFunction(device, display, &Display::setVsyncEnabled,
521                 enabled);
522     }
523 
524     class Layer {
525         public:
526             explicit Layer(Display& display);
527 
528             bool operator==(const Layer& other) { return mId == other.mId; }
529             bool operator!=(const Layer& other) { return !(*this == other); }
530 
getId()531             hwc2_layer_t getId() const { return mId; }
getDisplay()532             Display& getDisplay() const { return mDisplay; }
533 
534             // HWC2 Layer functions
535             HWC2::Error setBuffer(buffer_handle_t buffer, int32_t acquireFence);
536             HWC2::Error setCursorPosition(int32_t x, int32_t y);
537             HWC2::Error setSurfaceDamage(hwc_region_t damage);
538 
539             // HWC2 Layer state functions
540             HWC2::Error setBlendMode(HWC2::BlendMode mode);
541             HWC2::Error setColor(hwc_color_t color);
542             HWC2::Error setCompositionType(HWC2::Composition type);
543             HWC2::Error setDataspace(android_dataspace_t dataspace);
544             HWC2::Error setDisplayFrame(hwc_rect_t frame);
545             HWC2::Error setPlaneAlpha(float alpha);
546             HWC2::Error setSidebandStream(const native_handle_t* stream);
547             HWC2::Error setSourceCrop(hwc_frect_t crop);
548             HWC2::Error setTransform(HWC2::Transform transform);
549             HWC2::Error setVisibleRegion(hwc_region_t visible);
550             HWC2::Error setZ(uint32_t z);
551 
getCompositionType()552             HWC2::Composition getCompositionType() const {
553                 return mCompositionType;
554             }
getZ()555             uint32_t getZ() const { return mZ; }
556 
557             void addReleaseFence(int fenceFd);
558             const sp<MiniFence>& getReleaseFence() const;
559 
setHwc1Id(size_t id)560             void setHwc1Id(size_t id) { mHwc1Id = id; }
getHwc1Id()561             size_t getHwc1Id() const { return mHwc1Id; }
562 
563             // Write state to HWC1 communication struct.
564             void applyState(struct hwc_layer_1& hwc1Layer);
565 
566             std::string dump() const;
567 
getNumVisibleRegions()568             std::size_t getNumVisibleRegions() { return mVisibleRegion.size(); }
569 
getNumSurfaceDamages()570             std::size_t getNumSurfaceDamages() { return mSurfaceDamage.size(); }
571 
572             // True if a layer cannot be properly rendered by the device due
573             // to usage of SolidColor (a.k.a BackgroundColor in HWC1).
hasUnsupportedBackgroundColor()574             bool hasUnsupportedBackgroundColor() {
575                 return (mCompositionType == HWC2::Composition::SolidColor &&
576                         !mDisplay.getDevice().supportsBackgroundColor());
577             }
578         private:
579             void applyCommonState(struct hwc_layer_1& hwc1Layer);
580             void applySolidColorState(struct hwc_layer_1& hwc1Layer);
581             void applySidebandState(struct hwc_layer_1& hwc1Layer);
582             void applyBufferState(struct hwc_layer_1& hwc1Layer);
583             void applyCompositionType(struct hwc_layer_1& hwc1Layer);
584 
585             static std::atomic<hwc2_layer_t> sNextId;
586             const hwc2_layer_t mId;
587             Display& mDisplay;
588 
589             FencedBuffer mBuffer;
590             std::vector<hwc_rect_t> mSurfaceDamage;
591 
592             HWC2::BlendMode mBlendMode;
593             hwc_color_t mColor;
594             HWC2::Composition mCompositionType;
595             hwc_rect_t mDisplayFrame;
596             float mPlaneAlpha;
597             const native_handle_t* mSidebandStream;
598             hwc_frect_t mSourceCrop;
599             HWC2::Transform mTransform;
600             std::vector<hwc_rect_t> mVisibleRegion;
601 
602             uint32_t mZ;
603 
604             DeferredFence mReleaseFence;
605 
606             size_t mHwc1Id;
607             bool mHasUnsupportedPlaneAlpha;
608     };
609 
610     // Utility tempate calling a Layer object method based on ID parameters:
611     // hwc2_display_t displayId
612     // and
613     // hwc2_layer_t layerId
614     template <typename ...Args>
callLayerFunction(hwc2_device_t * device,hwc2_display_t displayId,hwc2_layer_t layerId,HWC2::Error (Layer::* member)(Args...),Args...args)615     static int32_t callLayerFunction(hwc2_device_t* device,
616             hwc2_display_t displayId, hwc2_layer_t layerId,
617             HWC2::Error (Layer::*member)(Args...), Args... args) {
618         auto result = getAdapter(device)->getLayer(displayId, layerId);
619         auto error = std::get<HWC2::Error>(result);
620         if (error == HWC2::Error::None) {
621             auto layer = std::get<Layer*>(result);
622             error = ((*layer).*member)(std::forward<Args>(args)...);
623         }
624         return static_cast<int32_t>(error);
625     }
626 
627     template <typename MF, MF memFunc, typename ...Args>
layerHook(hwc2_device_t * device,hwc2_display_t displayId,hwc2_layer_t layerId,Args...args)628     static int32_t layerHook(hwc2_device_t* device, hwc2_display_t displayId,
629             hwc2_layer_t layerId, Args... args) {
630         return HWC2On1Adapter::callLayerFunction(device, displayId, layerId,
631                 memFunc, std::forward<Args>(args)...);
632     }
633 
634     // Layer state functions
635 
setLayerBlendModeHook(hwc2_device_t * device,hwc2_display_t display,hwc2_layer_t layer,int32_t intMode)636     static int32_t setLayerBlendModeHook(hwc2_device_t* device,
637             hwc2_display_t display, hwc2_layer_t layer, int32_t intMode) {
638         auto mode = static_cast<HWC2::BlendMode>(intMode);
639         return callLayerFunction(device, display, layer,
640                 &Layer::setBlendMode, mode);
641     }
642 
setLayerCompositionTypeHook(hwc2_device_t * device,hwc2_display_t display,hwc2_layer_t layer,int32_t intType)643     static int32_t setLayerCompositionTypeHook(hwc2_device_t* device,
644             hwc2_display_t display, hwc2_layer_t layer, int32_t intType) {
645         auto type = static_cast<HWC2::Composition>(intType);
646         return callLayerFunction(device, display, layer,
647                 &Layer::setCompositionType, type);
648     }
649 
setLayerDataspaceHook(hwc2_device_t * device,hwc2_display_t display,hwc2_layer_t layer,int32_t intDataspace)650     static int32_t setLayerDataspaceHook(hwc2_device_t* device,
651             hwc2_display_t display, hwc2_layer_t layer, int32_t intDataspace) {
652         auto dataspace = static_cast<android_dataspace_t>(intDataspace);
653         return callLayerFunction(device, display, layer, &Layer::setDataspace,
654                 dataspace);
655     }
656 
setLayerTransformHook(hwc2_device_t * device,hwc2_display_t display,hwc2_layer_t layer,int32_t intTransform)657     static int32_t setLayerTransformHook(hwc2_device_t* device,
658             hwc2_display_t display, hwc2_layer_t layer, int32_t intTransform) {
659         auto transform = static_cast<HWC2::Transform>(intTransform);
660         return callLayerFunction(device, display, layer, &Layer::setTransform,
661                 transform);
662     }
663 
setLayerZOrderHook(hwc2_device_t * device,hwc2_display_t display,hwc2_layer_t layer,uint32_t z)664     static int32_t setLayerZOrderHook(hwc2_device_t* device,
665             hwc2_display_t display, hwc2_layer_t layer, uint32_t z) {
666         return callDisplayFunction(device, display, &Display::updateLayerZ,
667                 layer, z);
668     }
669 
670     // Adapter internals
671 
672     void populateCapabilities();
673     Display* getDisplay(hwc2_display_t id);
674     std::tuple<Layer*, HWC2::Error> getLayer(hwc2_display_t displayId,
675             hwc2_layer_t layerId);
676     void populatePrimary();
677 
678     bool prepareAllDisplays();
679     std::vector<struct hwc_display_contents_1*> mHwc1Contents;
680     HWC2::Error setAllDisplays();
681 
682     // Callbacks
683     void hwc1Invalidate();
684     void hwc1Vsync(int hwc1DisplayId, int64_t timestamp);
685     void hwc1Hotplug(int hwc1DisplayId, int connected);
686 
687     // These are set in the constructor and before any asynchronous events are
688     // possible
689 
690     struct hwc_composer_device_1* const mHwc1Device;
691     const uint8_t mHwc1MinorVersion;
692     bool mHwc1SupportsVirtualDisplays;
693     bool mHwc1SupportsBackgroundColor;
694 
695     class Callbacks;
696     const std::unique_ptr<Callbacks> mHwc1Callbacks;
697 
698     std::unordered_set<HWC2::Capability> mCapabilities;
699 
700     // These are only accessed from the main SurfaceFlinger thread (not from
701     // callbacks or dump
702 
703     std::map<hwc2_layer_t, std::shared_ptr<Layer>> mLayers;
704 
705     // A HWC1 supports only one virtual display.
706     std::shared_ptr<Display> mHwc1VirtualDisplay;
707 
708     // These are potentially accessed from multiple threads, and are protected
709     // by this mutex. This needs to be recursive, since the HWC1 implementation
710     // can call back into the invalidate callback on the same thread that is
711     // calling prepare.
712     std::recursive_timed_mutex mStateMutex;
713 
714     struct CallbackInfo {
715         hwc2_callback_data_t data;
716         hwc2_function_pointer_t pointer;
717     };
718     std::unordered_map<HWC2::Callback, CallbackInfo> mCallbacks;
719     bool mHasPendingInvalidate;
720 
721     // There is a small gap between the time the HWC1 module is started and
722     // when the callbacks for vsync and hotplugs are registered by the
723     // HWC2on1Adapter. To prevent losing events they are stored in these arrays
724     // and fed to the callback as soon as possible.
725     std::vector<std::pair<int, int64_t>> mPendingVsyncs;
726     std::vector<std::pair<int, int>> mPendingHotplugs;
727 
728     // Mapping between HWC1 display id and Display objects.
729     std::map<hwc2_display_t, std::shared_ptr<Display>> mDisplays;
730 
731     // Map HWC1 display type (HWC_DISPLAY_PRIMARY, HWC_DISPLAY_EXTERNAL,
732     // HWC_DISPLAY_VIRTUAL) to Display IDs generated by HWC2on1Adapter objects.
733     std::unordered_map<int, hwc2_display_t> mHwc1DisplayMap;
734 };
735 
736 } // namespace android
737 
738 #endif
739